How can I add a custom HTTP header to ajax request with js or jQuery?

前端 未结 9 1350
独厮守ぢ
独厮守ぢ 2020-11-22 03:17

Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?

9条回答
  •  感动是毒
    2020-11-22 04:00

    Here's an example using 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++;
    }; 
    

    Hope that helps.

    If you create your object, you can use the setRequestHeader function to assign a name, and a value before you send the request.

提交回复
热议问题