如何使用 jQuery 的 getJSON() 方法传递请求标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3229823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:03:31  来源:igfitidea点击:

How can I pass request headers with jQuery's getJSON() method?

jquerygetjson

提问by Berty

I need to do a getJSON()request, but how do I pass authorisation and custom headers?

我需要做一个getJSON()请求,但我如何传递授权和自定义标头?

I am getting issues that the request header is taking the name, but NOT the values. The URL is being shown through a manual request in fiddler to being inserted in as options instead of GET/Url.

我遇到的问题是请求标头采用名称,而不是值。URL 是通过 fiddler 中的手动请求显示为作为选项而不是 GET/Url 插入的。

Here is an example of what we are trying to do that works fine in fiddler; how can I replicate this with the AJAX function?

这是我们正在尝试做的在 fiddler 中运行良好的示例;如何使用 AJAX 函数复制它?

GET /Service.svc/logins/gdd53535342/houses/vxcbdfsdg/people/dsgsdggd?format=json HTTP/1.1
User-Agent: Fiddler
Authorization: Basic rgbg423535fa23y4436
X-PartnerKey: df3fgeg-g5g6-b55b-f3d2-dsgg353523
Host: 154.34.53.54:2757

JavaScript code:

JavaScript 代码:

xhr = new XMLHttpRequest();

$(document).ready(function() {
  $.ajax({
    url: 'http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json',
    type: 'GET',
    datatype: 'json',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader       
  });   
});

function setHeader(xhr) {
  xhr.setRequestHeader('Authorization', 'Basic faskd52352rwfsdfs');
  xhr.setRequestHeader('X-PartnerKey', '3252352-sdgds-sdgd-dsgs-sgs332fs3f');
}

Fiddler Normal Request Headers:

Fiddler 正常请求标头:

GET /service.svc/logins/jeffrey/house/fas6347/devices?format=json HTTP/1.1
User-Agent: Fiddler
Authorization: Basic faskd52352rwfsdfs
X-PartnerKey: 3252352-sdgds-sdgd-dsgs-sgs332fs3f
Host: localhost:437

Fiddler Through Ajax()Request Headers:

Fiddler 通过Ajax()请求标头:

OPTIONS service.svc/logins/jeffrey/house/fas6347/devices?format=json HTTP/1.1
Host: localhost:437
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Proxy-Connection: keep-alive
Origin: http://ipv4.fiddler:61975
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization,x-partnerkey

回答by David Hoerster

I agree with sunetos that you'll have to use the $.ajax function in order to pass request headers. In order to do that, you'll have to write a function for the beforeSend event handler, which is one of the $.ajax() options. Here's a quick sample on how to do that:

我同意 sunetos 您必须使用 $.ajax 函数才能传递请求标头。为此,您必须为 beforeSend 事件处理程序编写一个函数,它是 $.ajax() 选项之一。这是有关如何执行此操作的快速示例:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $.ajax({
          url: 'service.svc/Request',
          type: 'GET',
          dataType: 'json',
          success: function() { alert('hello!'); },
          error: function() { alert('boo!'); },
          beforeSend: setHeader
        });
      });

      function setHeader(xhr) {
        xhr.setRequestHeader('securityCode', 'Foo');
        xhr.setRequestHeader('passkey', 'Bar');
      }
    </script>
  </head>
  <body>
    <h1>Some Text</h1>
  </body>
</html>

If you run the code above and watch the traffic in a tool like Fiddler, you'll see two requests headers passed in:

如果您运行上面的代码并在 Fiddler 等工具中观察流量,您将看到传入的两个请求标头:

  • securityCode with a value of Foo
  • passkey with a value of Bar
  • 值为 Foo 的 securityCode
  • 值为 Bar 的密钥

The setHeader function could also be inline in the $.ajax options, but I wanted to call it out.

setHeader 函数也可以内联在 $.ajax 选项中,但我想调用它。

Hope this helps!

希望这可以帮助!

回答by Sean N.

I think you could set the headers and still use getJSON() like this:

我认为您可以设置标题并仍然使用 getJSON() 像这样:

$.ajaxSetup({
  headers : {
    'Authorization' : 'Basic faskd52352rwfsdfs',
    'X-PartnerKey' : '3252352-sdgds-sdgd-dsgs-sgs332fs3f'
  }
});
$.getJSON('http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json', function(json) { alert("Success"); }); 

回答by sunetos

The $.getJSON()method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax()method.

$.getJSON()方法是速记,不允许您指定类似的高级选项。为此,您需要使用完整$.ajax()方法。

Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:

http://api.jquery.com/jQuery.getJSON/的文档中注意:

This is a shorthand Ajax function, which is equivalent to:

这是一个简写的 Ajax 函数,相当于:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

So just use $.ajax()and provide all the extra parameters you need.

所以只需使用$.ajax()并提供您需要的所有额外参数。