跨域 AJAX 不发送 X-Requested-With 标头 [英] Cross-Domain AJAX doesn't send X-Requested-With header

查看:41
本文介绍了跨域 AJAX 不发送 X-Requested-With 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://www.a.com/service.asmx 上创建一个 Web 服务,并从 http://www.b 向它发送一个跨域的 ajax 请求.com.在 FirebugLive HTTP Headers 或您希望的任何其他插件中检查标头.

Create a web service on http://www.a.com/service.asmx and 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.

请求标头中没有 X-Requested-With HTTP 标头字段的踪迹.

There is no trace of the X-Requested-With HTTP Header field among request headers.

但是,如果您向来自同一域的同一服务发送 ajax 请求(例如 http://www.a.com/about),您将看到该标头字段.

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.

为什么跨域ajax请求省略了X-Requested-With标头字段?

Why is the X-Requested-With header field omitted for cross-domain ajax requests?

更新:我知道 JSONP 调用本质上不是 AJAX 调用.因此,您不会在 JSONP 调用中看到任何 X-Requested-With 标头字段.

Update: I know that JSONP calls are not AJAX calls in nature. Thus you won't see any X-Requested-With header field, in JSONP calls.

推荐答案

如果你使用 jQuery 做你的 ajax 请求,它不会发送头 X-Requested-With (HTTP_X_REQUESTED_WITH) = XMLHttpRequest,因为它是跨域的.但是有两种方法可以解决此问题并发送标头:

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:

选项1)在ajax调用中手动设置header:

Option 1) Manually set the header in the ajax call:

$.ajax({
     url: "http://your-url...",
 headers: {'X-Requested-With': 'XMLHttpRequest'}
});  

选项 2) 告诉 jQuery 不要使用跨域默认值,因此它将在 ajax 请求中保留 X-Requested-With 标头:

Option 2) Tell jQuery not to use cross domain defaults, so it will keep the X-Requested-With header in the ajax request:

$.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: *
";
print "Access-Control-Allow-Headers: X-Requested-With, Content-Type
";

上面的第一行将避免错误Origin is not allowed by Access-Control-Allow-Origin."
第二行将避免错误请求头字段 X-Requested-With is not allowed by Access-Control-Allow-Headers."

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."

这篇关于跨域 AJAX 不发送 X-Requested-With 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆