Can you add headers to getJSON in jQuery?

一笑奈何 提交于 2019-11-29 07:51:13

$.getJSON is a shorthand for

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

So you can simply use it directly like

$.ajax({
    beforeSend: function(request) {
        request.setRequestHeader("X-Mashape-Key", 'key_here');
    },
    dataType: "json",
    url: settings.apiPath + settings.username + '/boards/',
    success: function(data) {
        //Your code
    }
});

using $.ajax() would have been better, as $.getJSON is shorthand function, if you cant use $.ajax(), you can use $.ajaxSetup to set headers, as:

$.ajaxSetup({
  headers : {   
    'X-Mashape-Key' : 'key_here'
  }
});
$.getJSON(settings.apiPath + settings.username + '/boards/', function (data) {
 ...

But note that it sets headers for future Ajax requests.

jsshah

Since getJSON is a shortcut notation for $.ajax() why not use that

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

ajax() provides a hook called which you can specify by beforeSend: function(jqXHR, settings)

The hook allows one to add custom headers to outgoing AJAX request ... I think unlike $.ajaxSetup ... you do not have to worry about unsetting after using it

Don't think you can set headers on getJSON. http://api.jquery.com/jQuery.getJSON/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!