Jak Mogę dodać niestandardowy nagłówek HTTP do żądania ajax za pomocą js lub jQuery?

Czy ktoś wie jak dodać lub utworzyć niestandardowy nagłówek HTTP za pomocą JavaScript lub jQuery?

Author: Prestaul, 2011-10-07

8 answers

Istnieje kilka rozwiązań w zależności od tego, czego potrzebujesz...

Jeśli chcesz dodać niestandardowy nagłówek (lub zestaw nagłówków) do indywidualnego żądania, po prostu dodaj Właściwość headers:

// Request with custom header
$.ajax({
    url: 'foo/bar',
    headers: { 'x-my-custom-header': 'some value' }
});

Jeśli chcesz dodać domyślny nagłówek (lub zestaw nagłówków) do każdego żądania, użyj $.ajaxSetup():

$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

Jeśli chcesz dodać nagłówek (lub zestaw nagłówków) do każdego żądania, użyj Hooka beforeSend z $.ajaxSetup():

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

Edycja (więcej info): Należy pamiętać, że z ajaxSetup można zdefiniować tylko jeden zestaw domyślnych nagłówków i można zdefiniować tylko jeden beforeSend. Jeśli wywołasz ajaxSetup wiele razy, zostanie wysłany tylko ostatni zestaw nagłówków i zostanie wywołana tylko ostatnia funkcja callback before-send.

 528
Author: Prestaul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-15 15:33:47

Lub, jeśli chcesz wysłać niestandardowy nagłówek dla każdego przyszłego żądania, możesz użyć następującego polecenia:

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

W ten sposób każde przyszłe żądanie ajax będzie zawierać niestandardowy nagłówek, chyba że zostanie wyraźnie nadpisane przez opcje żądania. Więcej informacji można znaleźć na ajaxSetup tutaj

 49
Author: Szilard Muzsi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-16 07:50:00

Zakładając JQuery ajax, możesz dodać własne nagłówki jak -

$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("custom_header", "value");
  },
  success: function(data) {
  }
});
 17
Author: Jayendra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-07 11:58:52

Oto przykład użycia 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++;
}; 
Mam nadzieję, że to pomoże.

Jeśli tworzysz swój obiekt, możesz użyć funkcji setRequestHeader, aby przypisać nazwę i wartość przed wysłaniem żądania.

 16
Author: James,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-10 08:46:40

Możesz to zrobić również bez użycia jQuery. Zastąp metodę wysyłania XMLHttpRequest i dodaj tam nagłówek:

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;
 14
Author: Roland T.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-25 11:04:01

Należy unikać używania $.ajaxSetup()w sposób opisany w docs. Użyj zamiast tego:

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    jqXHR.setRequestHeader('my-custom-header', 'my-value');
});
 12
Author: Stefan D.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-12 19:39:43

Zakładając, że masz na myśli "Podczas korzystania z ajax" i "żądanie HTTP header", użyj właściwości headers w obiekcie, który przekazujesz ajax()

Headers (added 1.5)

Default: {}

Mapa dodatkowych par nagłówka klucz / wartość do wysłania wraz z żądaniem. To ustawienie jest ustawiane przed wywołaniem funkcji beforeSend; dlatego wszelkie wartości w Ustawieniach nagłówków mogą być nadpisane z poziomu funkcji beforeSend.

- http://api.jquery.com/jQuery.ajax/

 6
Author: Quentin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-07 11:56:28

Należy użyć metody"setRequestHeader" obiektu XMLHttpRequest

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

 3
Author: 4esn0k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-07 11:59:27