有人知道如何使用JavaScript或jQuery添加或创建自定义HTTP头吗?


当前回答

或者,如果你想为以后的每个请求发送自定义报头,那么你可以使用以下方法:

$.ajaxSetup({
    headers: { "CustomHeader": "myValue" }
});

这样,以后的每个ajax请求都将包含自定义头,除非被请求的选项显式地覆盖。你可以在这里找到更多关于ajaxSetup的信息

其他回答

使用XMLHttpRequest对象的“setRequestHeader”方法

http://help.dottoro.com/ljhcrlbv.php

假设JQuery ajax,您可以添加自定义标题,如-

$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("custom_header", "value");
  },
  success: function(data) {
  }
});

或者,如果你想为以后的每个请求发送自定义报头,那么你可以使用以下方法:

$.ajaxSetup({
    headers: { "CustomHeader": "myValue" }
});

这样,以后的每个ajax请求都将包含自定义头,除非被请求的选项显式地覆盖。你可以在这里找到更多关于ajaxSetup的信息

下面是一个使用XHR2的例子:

function xhrToSend(){
    // Attempt to creat the XHR2 object
    var xhr;
    try{
        xhr = new XMLHttpRequest();
    }catch (e){
        try{
            xhr = new XDomainRequest();
        } catch (e){
            try{
                xhr = new ActiveXObject('Msxml2.XMLHTTP');
            }catch (e){
                try{
                    xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }catch (e){
                    statusField('\nYour browser is not' + 
                        ' compatible with XHR2');                           
                }
            }
        }
    }
    xhr.open('POST', 'startStopResume.aspx', true);
    xhr.setRequestHeader("chunk", numberOfBLObsSent + 1);
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState == 4 && xhr.status == 200) {
            receivedChunks++;
        }
    };
    xhr.send(chunk);
    numberOfBLObsSent++;
}; 

希望这能有所帮助。

如果创建对象,可以在发送请求之前使用setRequestHeader函数分配名称和值。

不使用jQuery也可以做到这一点。重写XMLHttpRequest的send方法,并在那里添加报头:

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
    this.setRequestHeader('x-my-custom-header', 'some value');
    this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;