跨域Ajax不发送的X请求,使用包头 [英] Cross-Domain AJAX doesn't send X-Requested-With header

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

问题描述

在创建Web服务的 http://www.a.com/service.asmx 并发送一个跨域Ajax请求将其从的http://www.b。 COM 。检查标题中的萤火虫,或已HTTP标头,或其他任何插件,您希望。

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-要求 - 以 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.

为什么在 X-要求 - 以报头字段省略跨域Ajax请求?

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

更新:我知道JSONP调用无法在自然界AJAX调用。因此,你将不会看到任何的 X-要求 - 以报头字段,在JSONP调用。

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请求 - 由于(HTTP_X_REQUESTED_WITH)= XMLHtt prequest,因为它是跨域。但也有2种方式来解决这个问题,发送标题:

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调用:

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

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

选项2)推荐的jQuery不使用跨域违约,因此它将保持在X-要求,随着头部的Ajax请求:

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

上面的第一行会避免错误的原产地不是由访问控制 - 允许 - 产地允许的。
请求头字段的X请求 - 由于不受访问控制 - 允许 - 头不允许的。第二个行会避免错误

这篇关于跨域Ajax不发送的X请求,使用包头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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