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

前端 未结 3 697
迷失自我
迷失自我 2020-12-04 17:07

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

I am getting issues that the request header is taking the name, bu

相关标签:
3条回答
  • 2020-12-04 17:49

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

    $.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"); }); 
    
    0 讨论(0)
  • 2020-12-04 17:53

    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.

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

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

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

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

    0 讨论(0)
  • 2020-12-04 18:08

    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:

    <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:

    • securityCode with a value of Foo
    • passkey with a value of Bar

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

    Hope this helps!

    0 讨论(0)
提交回复
热议问题