本地主机与IP地址之间的差异Ajax请求发送 [英] Difference between localhost and IP address in Ajax request sending
问题描述
我有一个奇怪的问题,原生Ajax请求调用。
I have a strange problem with native Ajax request invoking.
我创建Ajax对象和发送请求类似如下:
I am creating the Ajax object and sending the request like follows:
var xmlHttpObj = new XMLHttpRequest();
...
xmlHttpObj.open("GET","http://192.168.16.254:8080/ajax/demoExample.html",true);
xmlHttpObj.send();
当我访问servlet的URL像的http://本地主机:8080 / AJAX ...
,
那么我没能获得在客户端的响应。但我可以看到在服务器端的响应。
When I access the servlet with the URL something like http://localhost:8080/ajax...
,
then I am not able to get the response in the client side. But I can see the response in the server side.
pretty的类似的方式
Pretty similar way I invoked the request with
xmlHttpObj.open("GET","http://localhost:8080/ajax/demoExample.html",true);
和我的网址是的http://192.168.16.254:8080 / AJAX ...
,然后还要我不能够看到我的客户端的响应。
and my URL is http://192.168.16.254:8080/ajax...
, then also I am not able to see the response in my client side.
我知道要解决这个问题的最好办法。
I know the best way to fix the problem.
我可以调用与请求
xmlHttpObj.open("GET","../ajax/demoExample.html",true);
xmlHttpObj.send();
那么我没有与localhost或IP地址的任何问题。
then I don't have any problem with either localhost or IP address.
但我仍觉得这是为什么在AJAX请求本地主机与IP地址之间的差异。
But still I think why is the difference between localhost and IP address in ajax requesting.
推荐答案
这更多的不是一个问题,一个安全功能:
It's more of a security feature than a problem :
借助同源策略 prevents一个 文档或脚本从一个装 获取或设置原点 一个文件,从另一个特性 由来。
The same origin policy prevents a document or script loaded from one origin from getting or setting properties of a document from another origin.
本地主机和192.168.16.254被认为是不同的起源。这同样适用于两个主机名指向同一个地址,因为他们可以(而且很可能会)指向同一服务器上的不同网站/应用程序。 AFAIK解决这个问题的唯一方法是使用 IFRAME
内容或 JSONP
了解JSON。虽然你的情况相对URL是要走的路。
localhost and 192.168.16.254 are considered different origins. The same goes for two hostnames that point to the same address as they could (and probably will) point to a different site/application on the same server. AFAIK the only way around this is to use iframe
for content or JSONP
for json. Although in your case relative URLs is the way to go.
这篇关于本地主机与IP地址之间的差异Ajax请求发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!