Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you add headers to getJSON in jQuery?

ive been looking to get JSON data for pinterest but notice they currently dont let you get for a user and a specific board so found mashape and i need to get the API key but using header request can this be done using getJSON? current code is:

I need to pass: "X-Mashape-Key: KEY_HERE" i see it can be done in ajax but dont know how to rewrite the getJSON as the loop to that but can see here:

http://blog.mashape.com/mashape-sample-code-executing-ajax-request-using-jquery/

$.getJSON(settings.apiPath + settings.username + '/boards/', function (data) {
            beforeSend: setHeader,
            console.log(data);

            for (var i = 0; i < settings.count; i++) {
                var feed = false;
                if(data.data[i]) {
                    feed = data.data[i];
                }

                var temp_data = {
                    message: truncate(feed["message"], 100),
                    url: feed["link"]
                };

                $('#pinterestFeed ul').append('<li class="feed">' + templating(temp_data) + '</li>');
            }
            $(".pinterest #loading").hide();  
        });
like image 842
James Brandon Avatar asked Jul 29 '14 09:07

James Brandon


People also ask

What is the difference between getJSON and ajax in jQuery?

getJSON() is equal to $. ajax() with dataType set to "json", which means that if something different than JSON is returned, you end up with a parse error. So you were mostly right about the two being pretty much the same :).

Is getJSON an ajax call?

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

What are the arguments of getJSON method?

It is a callback function that executes on the successful server request. It also has three parameters that are data, status, and xhr in which data contains the data returned from the server, status represents the request status like "success", "error", etc., and the xhr contains the XMLHttpRequest object.

How jQuery read data from JSON file?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.


1 Answers

$.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
    }
});
like image 69
Satpal Avatar answered Oct 06 '22 18:10

Satpal