您将无法进行 ajax 调用http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
来自部署在的文件http://run.jsbin.com
因为同源策略 http://en.wikipedia.org/wiki/Same-origin_policy.
作为来源(又名origin)页面和targetURL 位于不同的域(run.jsbin.com
and www.ecb.europa.eu
),你的代码实际上是试图做一个跨域(CORS) http://en.wikipedia.org/wiki/Cross-origin_resource_sharing请求,不是普通的请求GET
.
简而言之,同源策略说浏览器应该只允许 ajax 调用服务相同的域HTML 页面的。
Example:
页面位于http://www.example.com/myPage.html
只能直接请求位于http://www.example.com
, like http://www.example.com/api/myService
。如果该服务托管在另一个域中(例如http://www.ok.com/api/myService
),浏览器不会直接进行调用(如您所料)。相反,它会尝试发出 CORS 请求。
简而言之,要跨不同域执行 (CORS) 请求*,您的浏览器:
- 将包括一个
Origin
原始请求中的标头(以页面的域作为值)并照常执行;进而
-
Only if the server response to that request contains the adequate headers (Access-Control-Allow-Origin is one of them) http://enable-cors.org/server.html allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
- 如果预期的标头没有出现,浏览器就会放弃(就像它对您所做的那样)。
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers https://stackoverflow.com/questions/1557602/jquery-and-ajax-response-header/15444439#15444439 header.
如何修复它?
这只是一个错字吗?有时,JavaScript 代码只是在目标域中存在拼写错误。你检查过吗?如果页面位于www.example.com
它只会定期调用www.example.com
!其他网址,例如api.example.com
甚至example.com
or www.example.com:8080
被考虑不同的浏览器的域名!是的,如果端口不同,那么它就是不同的域!
添加标题。最简单的方法enableCORS 是通过添加必要的标头(如Access-Control-Allow-Origin
)到服务器的响应。 (每种服务器/语言都有一种方法可以做到这一点 -在这里检查一些解决方案 http://enable-cors.org.)
最后一招:如果您没有服务器端访问该服务的权限,您也可以对其进行镜像(通过诸如反向代理),并在其中包含所有必要的标头。