在jQuery AJAX GET调用中传递请求标头

时间:2010-07-15 18:25:56

标签: jquery ajax client-side

我正在尝试使用jQuery在AJAX GET中传递请求标头。在下面的块中,“data”会自动传递查询字符串中的值。有没有办法在请求标头中传递该数据?

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

以下不起作用

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

3 个答案:

答案 0 :(得分:355)

从jQuery 1.5开始,您可以传递headers哈希,如下所示:

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

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

  

标头(已添加1.5):要与请求一起发送的其他标头键/值对的映射。在调用beforeSend函数之前设置此设置;因此,可以从beforeSend函数中覆盖标题设置中的任何值。

答案 1 :(得分:261)

使用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 :(得分:34)

$.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) {
                
            }
        });

相关问题