Hub*_*bro 7 javascript ajax xmlhttprequest
我收到此JavaScript错误
XMLHttpRequest无法加载http://foo.bar.no/API/map_tools/clean_addresses/check.Access-Control-Allow-Origin不允许来源http://foo.bar.no:9294.
这些都在同一个域和相同的服务器上,但我的JavaScript项目由一个独立的服务器脚本托管,该脚本自动将JavaScript及其依赖项捆绑到一个文件中.
在我开发的过程中如何克服这个限制?
我试过允许我的JavaScript服务器脚本连接.这是网址卷曲的结果:
HTTP/1.1 200 OK
Date: Wed, 11 Jan 2012 09:05:14 GMT
Server: Apache/2.2.16 (Debian)
Access-Control-Allow-Origin: http://foo.bar.no:9294
Vary: Accept-Encoding
Content-Length: 70
Content-Type: text/plain
array(1) {
["q"]=>
string(31) "map_tools/clean_addresses/check"
}
而且我仍然得到与上面粘贴完全相同的错误.为什么当显然允许时,Chrome仍然拒绝连接到该死的URL!?
好吧,我想通了。我一直在寻找一种简单而快速的修复方法,因为我只需要跨域请求来进行开发。事实证明我只需要同时设置两个
header("Access-Control-Allow-Origin: http://foo.bar.no:9294");
header("Access-Control-Allow-Credentials: true");
Run Code Online (Sandbox Code Playgroud)
在我的 Apache 上的 PHP 脚本中。然后在我的 JavaScript 代码中:
# Set jQuery ajax to use 'withCredentials' globally
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
Run Code Online (Sandbox Code Playgroud)
这成功了