我在调用 native Ajax 请求时遇到了一个奇怪的问题。
我正在创建 Ajax 对象并发送请求,如下所示:
var xmlHttpObj = new XMLHttpRequest();
...
xmlHttpObj.open("GET","http://192.168.16.254:8080/ajax/demoExample.html",true);
xmlHttpObj.send();
当我使用类似于 http://localhost:8080/ajax...
的 URL 访问 servlet 时,
那么我无法在客户端得到响应。但我可以在服务器端看到响应。
与我调用请求的方式非常相似
xmlHttpObj.open("GET","http://localhost:8080/ajax/demoExample.html",true);
我的 URL 是 http://192.168.16.254:8080/ajax...
,那么我也无法在客户端看到响应。
我知道解决问题的最佳方法。
我可以使用
调用请求xmlHttpObj.open("GET","../ajax/demoExample.html",true);
xmlHttpObj.send();
那么我的本地主机或 IP 地址都没有任何问题。
但我仍然认为为什么ajax请求中的localhost和IP地址之间存在差异。
最佳答案
与其说这是一个问题,不如说它是一个安全功能:
The same origin policy prevents a document or script loaded from one origin from getting or setting properties of a document from another origin.
localhost 和 192.168.16.254 被视为不同的来源。对于指向同一地址的两个主机名也是如此,因为它们可以(并且可能会)指向同一服务器上的不同站点/应用程序。据我所知,解决这个问题的唯一方法是使用 iframe
内容或 JSONP
对于 json.尽管在您的情况下相对 URL 是可行的方法。
关于javascript - Ajax发送请求时localhost和IP地址的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4181927/