Ajax请求发送中localhost和IP地址的区别 [英] Difference between localhost and IP address in Ajax request sending

查看:85
本文介绍了Ajax请求发送中localhost和IP地址的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在调用原生 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();

当我使用类似于 http://localhost:8080/ajax... 的 URL 访问 servlet 时,然后我无法在客户端获得响应.但是我可以在服务器端看到响应.

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.

与我使用

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

我的 URL 是 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();

那么我对本地主机或 IP 地址都没有任何问题.

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

但是我还是觉得为什么ajax请求中localhost和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 :

同源政策从一个加载的文档或脚本起源于获取或设置来自另一个文档的属性起源.

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 被认为是不同的来源.对于指向相同地址的两个主机名也是如此,因为它们可以(并且可能会)指向同一服务器上的不同站点/应用程序.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.

这篇关于Ajax请求发送中localhost和IP地址的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆