2

在我的代码中,我使用 jQuery 从不同域的另一台服务器获取一些 JSON,并在浏览器中出现错误。

XMLHttpRequest cannot load http://url_containing_json.com. Origin http://localhost:53651  is not allowed by Access-Control-Allow-Origin

将 Brackets 服务器配置为允许这样做是否容易?还是我需要设置自己的服务器才能做到这一点?

4

2 回答 2

0

This restriction comes from the web browser, not the server. It's called the same-origin security policy (aka the same-domain policy).

What is the http://url_containing_json.com "JSON server" in question? Is it a server you have some control over? If so, then you can either:

A) Upload your code to the "JSON server" itself so your site is served from that same domain; or

B) Upload your code to some other staging server, and use CORS on the JSON server to essentially whitelist the staging server's domain name (the JSON server would provide an Access-Control-Allow-Origin HTTP header, as mentioned in the error message).

On the other hand -- if the "JSON server" is completely third-party, does it actually want other sites like yours to be fetching its JSON? If so, then it should already support either CORS (with a blanket allow-all policy) or JSONP (an older way of allowing access, though your requests will need to be set up a little differently).

If the JSON server doesn't permit cross-domain requests, you have one last resort: use your own site's server as a proxy. Instead of your page pinging the JSON server directly, your page pings its own server, which then pings the JSON server on the page's behalf.

All these approaches require running your own server instead of using the built-in Brackets "localhost" server. You can point Brackets at your own server via File > Project Settings..., but be aware that will disable certain features like Live HTML Development. (Though if you're able to use option "B" above you could maybe hack your hosts file to keep using the built-in Brackets server instead by changing its apparent domain).

Hope that helps!

于 2013-10-02T07:59:39.040 回答
0

遇到了完全相同的问题。我解决这个问题的方法是使用 jsonp ajax 请求类型,使用 $.ajax() 调用的 dataType 参数。请参阅有关此调用的JQuery 文档。

于 2016-07-09T09:28:50.423 回答