<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script>
$.get("http://example.com/", function(data) {
     alert(data);
});
</script>

它对那个URL做一个OPTIONS请求,然后回调永远不会被调用任何东西。

当它不是跨域时,它工作得很好。

jQuery不应该只是调用一个<script>节点,然后在它加载时做回调吗?我知道我将无法得到的结果(因为它是跨域),但这是可以的;我只想让电话接通。这是bug,还是我做错了什么?


当前回答

我能够修复它与以下头的帮助

Access-Control-Allow-Origin
Access-Control-Allow-Headers
Access-Control-Allow-Credentials
Access-Control-Allow-Methods

如果你使用的是Nodejs,下面是你可以复制/粘贴的代码。

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin','*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH');
  next();
});

其他回答

看起来Firefox和Opera(在mac上也测试过)不喜欢这种交叉域(但Safari没问题)。

您可能必须调用本地服务器端代码来压缩远程页面。

根据MDN,

Preflighted requests Unlike simple requests (discussed above), "preflighted" requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if: It uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted. It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

OPTIONS来自http://www.w3.org/TR/cors/,请参阅http://metajack.im/2010/01/19/crossdomain-ajax-for-xmpp-http-binding-made-easy/了解更多信息

我能够修复它与以下头的帮助

Access-Control-Allow-Origin
Access-Control-Allow-Headers
Access-Control-Allow-Credentials
Access-Control-Allow-Methods

如果你使用的是Nodejs,下面是你可以复制/粘贴的代码。

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin','*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH');
  next();
});

在我的例子中,这个问题与CORS无关,因为我正在向同一个web服务器发出jQuery POST。数据是JSON,但我省略了dataType: ' JSON '参数。

正如上面David Lopes的回答所示,我没有(也没有添加)contentType参数。