如何发出跨域XHR请求
如何使有效的 XHR 跨域请求 - 我已经尝试过“Script Tag Hack”,但它不起作用或者我做错了什么。有什么建议吗?
我想从 B 调用域 A 中的脚本。
域 A: [index.html]
<head>
<script type="text/javascript" src="https://evilDomain/xhrTest.js"></script>
</head>
域 B: [xhrTest.js]
$.ajax({
url: "https://evilDomain/processRequest",
success: function(result){
alert(result);
}
});
已编辑 :
我也尝试以这种方式使用 JSONP:
$.ajax({
url: "https://evilDomain/processRequest",
dataType: "jsonp",
success: function(result){
alert(result);
}
});
我正在使用 TOMCAT 容器,解决方案是否与 Access-Control-Allow-Origin 标头连接?
How to make working XHR cross domain request - I've tried 'Script Tag Hack' but it doesn't work or I'm doing something wrong. Any suggestions?
I would like to call script in domain A from B.
domain A: [index.html]
<head>
<script type="text/javascript" src="https://evilDomain/xhrTest.js"></script>
</head>
domain B: [xhrTest.js]
$.ajax({
url: "https://evilDomain/processRequest",
success: function(result){
alert(result);
}
});
edited:
I've also tried to use JSONP in this way:
$.ajax({
url: "https://evilDomain/processRequest",
dataType: "jsonp",
success: function(result){
alert(result);
}
});
I'm using TOMCAT container, is the solution connected with Access-Control-Allow-Origin header?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您可以将 Access-Control-Allow-Origin 标头添加到服务器响应中。这将允许您发出跨域请求。
然后,您可以根据需要使用 Access-Control-Allow-Methods 和 Access-Control-Allow-Headers 进一步自定义。
有关更多详细信息,请参阅https://developer.mozilla.org/en/HTTP_access_control
Yes, you can add the Access-Control-Allow-Origin header to your server responses. This will allow you to make cross-domain requests.
You can then further customise as required with Access-Control-Allow-Methods and Access-Control-Allow-Headers.
For more details see https://developer.mozilla.org/en/HTTP_access_control
通常,您会要求服务器为您执行请求。
另一种选择是让其他人为您做这件事(例如雅虎的服务)。
您的问题是域 B 的代码仍然在域 A 的上下文中执行。
因此,
https://evilDomain/processRequest
仍然无法读取,因为代码作为域 A 执行,即使实际上它来自域 B >。Usually, you would ask your server to do the request for you.
The other option is to let someone else do that for you (such as Yahoo's service).
Your problem is that domain B's code is still executed in the context of domain A.
Hence,
https://evilDomain/processRequest
still cannot be read because the code is executing as domain A even if in truth it came from domain B.使用 JSONP 或让您自己的域上的服务调用服务器端的其他域并以这种方式获取您需要的内容。
use JSONP or have a service on your own domain call the other domain on the server-side and get what you need that way.
域B JS被包含在页面中,然后从源自域A的页面执行,因此出现问题。要执行此跨域操作,您需要将数据响应作为“脚本”本身请求,然后从那里解析它。
The domain B JS is being included in the page, then being executed from the page which originates from domain A, hence the problem. To do this cross domain you need to request the data response as a "script" itself, then parse it from there.