跨域 AJAX 不发送 X-Requested-With 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8163703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cross-Domain AJAX doesn't send X-Requested-With header
提问by Saeed Neamati
Create a web service on http://www.a.com/service.asmxand send a cross-domain ajax request to it from http://www.b.com. Check the headers in Firebug, or in Live HTTP Headers, or any other plugin you wish.
在http://www.a.com/service.asmx上创建一个 Web 服务,并从http://www.b.com向它发送跨域 ajax 请求。检查Firebug或Live HTTP Headers 中的标头,或您希望的任何其他插件。
There is no trace of the X-Requested-WithHTTP Header field among request headers.
请求头中没有X-Requested-WithHTTP Header 字段的踪迹。
However, if you send an ajax request to the same service from the same domain (say for example http://www.a.com/about), you will see that header field.
但是,如果您从同一域(例如http://www.a.com/about)向同一服务发送 ajax 请求,您将看到该标头字段。
Why is the X-Requested-Withheader field omitted for cross-domain ajax requests?
为什么跨域ajax请求省略了X-Requested-With头字段?
Update:I know that JSONP calls are not AJAX calls in nature. Thus you won't see any X-Requested-Withheader field, in JSONP calls.
更新:我知道 JSONP 调用本质上不是 AJAX 调用。因此,您不会在 JSONP 调用中看到任何X-Requested-With标头字段。
回答by Rodrigo De Almeida Siqueira
If you are using jQuery to do your ajax request, it will not send the header X-Requested-With (HTTP_X_REQUESTED_WITH) = XMLHttpRequest, because it is cross domain. But there are 2 ways to fix this and send the header:
如果您使用 jQuery 来执行 ajax 请求,它不会发送标头 X-Requested-With (HTTP_X_REQUESTED_WITH) = XMLHttpRequest,因为它是跨域的。但是有两种方法可以解决此问题并发送标头:
Option 1) Manually set the header in the ajax call:
选项 1) 在 ajax 调用中手动设置标头:
$.ajax({
url: "http://your-url...",
headers: {'X-Requested-With': 'XMLHttpRequest'}
});
Option 2) Tell jQuery not to use cross domain defaults, so it will keep the X-Requested-With header in the ajax request:
选项 2) 告诉 jQuery 不要使用跨域默认值,因此它将在 ajax 请求中保留 X-Requested-With 标头:
$.ajax({
url: "http://your-url...",
crossDomain: false
});
But with this, the server must allow those headers, then the server needs to print those headers:
但是有了这个,服务器必须允许这些标题,然后服务器需要打印这些标题:
print "Access-Control-Allow-Origin: *\n";
print "Access-Control-Allow-Headers: X-Requested-With, Content-Type\n";
The first line above will avoid the error "Origin is not allowed by Access-Control-Allow-Origin."
The second line will avoid the error "Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers."
上面的第一行将避免错误“Access-Control-Allow-Origin 不允许源”。
第二行将避免错误“请求头字段 X-Requested-With is not allowed by Access-Control-Allow-Headers”。

