添加标题在AJAX请求使用jQuery [英] Add Header in AJAX Request with jQuery
问题描述
我想自定义头部添加到从jQuery的一个AJAX POST请求。
I would like to add a custom header to an AJAX POST request from jQuery.
我已经试过这样:
$.ajax({
type: 'POST',
url: url,
headers: {
"My-First-Header":"first value",
"My-Second-Header":"second value"
}
//OR
//beforeSend: function(xhr) {
// xhr.setRequestHeader("My-First-Header", "first value");
// xhr.setRequestHeader("My-Second-Header", "second value");
//}
}).done(function(data) {
alert(data);
});
当我把这个请求,我看与萤火虫,我看到这样的标题:
When I send this request and I watch with FireBug, I see this header:
选项XXXX / YYYY HTTP / 1.1
主持人:127.0.0.1:6666
用户代理:Mozilla的/ 5.0(Windows NT的6.1; WOW64; RV:11.0)的Gecko / 20100101 Firefox的/ 11.0
接受:text / html的,是application / xhtml + xml的,应用程序/ XML; Q = 0.9, / 的; Q = 0.8
接受语言:FR,FR-FR; Q = 0.8,EN-US; Q = 0.5,连接; Q = 0.3
接受编码:gzip,紧缩
连接:保持活动
产地:空
访问控制请求-方法:POST
访问控制请求报头:我先报头,我-第二头
杂注:无缓存
的Cache-Control:no-cache的
OPTIONS xxxx/yyyy HTTP/1.1
Host: 127.0.0.1:6666
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
Access-Control-Request-Headers: my-first-header,my-second-header
Pragma: no-cache
Cache-Control: no-cache
为什么我的自定义页眉去访问控制请求报头
:
Why do my custom headers go to Access-Control-Request-Headers
:
访问控制请求报头:我先报头,我-第二头
Access-Control-Request-Headers: my-first-header,my-second-header
我期待一个报头值是这样的:
I was expecting a header values like this:
我的-第一头:第一个值
我-第二头:第二个值
My-First-Header: first value
My-Second-Header: second value
这可能吗?谢谢你。
推荐答案
您在Firefox中看到的是不实际的要求;注意,HTTP方法是OPTIONS,无法发布。这实际上是'pre-飞行的要求,该浏览器发出来确定一个跨域AJAX请求是否应该被允许的:
What you saw in Firefox was not the actual request; note that the HTTP method is OPTIONS, not POST. It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed:
在pre-飞行请求访问控制请求报头报头包含实际的请求头的列表。服务器则有望是否这些标头在这种情况下,或不支持之前,浏览器提交的实际要求汇报。
The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request.
这篇关于添加标题在AJAX请求使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!