我正在使用这个 webservice它返回一个 XML 文档。
当我使用 Ajax 调用此 Web 服务时,我得到:
XMLHttpRequest cannot load http://services.gisgraphy.com/geoloc/search?lat=36.81881&lng=10.16596&from=1&to=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.4:50000' is therefore not allowed access.
何时用 PHP 做同样的事情:
<?php
$xml = simplexml_load_file('http://services.gisgraphy.com/geoloc/search?lat=50.209298&lng=10.245&from=1&to=1');
print_r($xml);
?>
打印它不受限制。
我只是想知道这些情况之间的区别,以及为什么它只适用于 php 文件?
干杯。
最佳答案
当您运行 PHP 代码时,您是在自己的服务器上执行的。什么都不应该 限制您访问其他网站,因为它是您的服务器。
当您运行 Javascript 代码时,您通常会在客户端上运行它 网页浏览器。您不拥有客户端计算机。和客户端机器 想要保护自己免于连接到恶意网站。
假设没有同源策略:
$.ajax({
url: "http://somedrugdealingwebsite.com"
})
客户的IP将被注册为毒品交易网站的访问者。
关于javascript - 为什么同源策略限制访问 Ajax 而不是 Php?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24960364/