简体   繁体   中英

Difference between localhost and IP address in Ajax request sending

I have a strange problem with native Ajax request invoking.

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();

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 similar way I invoked the request with

xmlHttpObj.open("GET","http://localhost:8080/ajax/demoExample.html",true);

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.

I can invoke the request with

xmlHttpObj.open("GET","../ajax/demoExample.html",true);
xmlHttpObj.send();

then I don't have any problem with either localhost or IP address.

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 :

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM