Pass request headers in a jQuery AJAX GET call

2019-01-01 05:16发布

问题:

I am trying to pass request headers in an AJAX GET using jQuery. In the following block, \"data\" automatically passes the values in the querystring. Is there a way to pass that data in the request header instead ?

$.ajax({
         url: \"http://localhost/PlatformPortal/Buyers/Account/SignIn\",
         data: { signature: authHeader },
         type: \"GET\",
         success: function() { alert(\'Success!\' + authHeader); }
      });

The following didn\'t work either

$.ajax({
         url: \"http://localhost/PlatformPortal/Buyers/Account/SignIn\",
         beforeSend: { signature: authHeader },
         async: false,                    
         type: \"GET\",
                    success: function() { alert(\'Success!\' + authHeader); }
      });

回答1:

Use beforeSend:

$.ajax({
         url: \"http://localhost/PlatformPortal/Buyers/Account/SignIn\",
         data: { signature: authHeader },
         type: \"GET\",
         beforeSend: function(xhr){xhr.setRequestHeader(\'X-Test-Header\', \'test-value\');},
         success: function() { alert(\'Success!\' + authHeader); }
      });

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

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method



回答2:

As of jQuery 1.5, there is a headers hash you can pass in as follows:

$.ajax({
    url: \"/test\",
    headers: {\"X-Test-Header\": \"test-value\"}
});

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

headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.



回答3:

$.ajax({
            url: URL,
            type: \'GET\',
            dataType: \'json\',
            headers: {
                \'header1\': \'value1\',
                \'header2\': \'value2\'
            },
            contentType: \'application/json; charset=utf-8\',
            success: function (result) {
               // CallBack(result);
            },
            error: function (error) {
                
            }
        });