Leonardo
Leonardo

Reputation: 4228

JQuery JSONP randomly generated callback function

I'm using JQuery to make JSONP requests and the documentation is quite confusing.

I have several questions:

Here's my code:

(function($) {
    var url = "https://www.googleapis.com/books/v1/volumes/zyTCAlFPjgYC";
    $.ajax({
        type: 'GET',
        url: url,
        // JSONP always async?
        async: false,
        jsonp: "callback",
        jsonpCallback: 'jsonCallback',
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(json) {
            console.dir(json);
        },
        // Error never called?
        error: function(e) {
            console.log(e.message);
        }
    });
})(jQuery);

function jsonCallback(json) {
    $(".test").html(json.volumeInfo.title);
}

Upvotes: 0

Views: 2731

Answers (1)

dev_row
dev_row

Reputation: 162

A JSONP call is always async, is that correct? So the async:false would be simply ignored?

That is correct

If the jsonpCallback parameter is specified, this function will be executed when the data are retrieved. But right after, also the success callback will be executed. Jquery advices NOT to specify the jsonpCallback function(only for caching?). What is the role of this function in relation with the success function?

The success function is your callback. Jquery generates a random function name usually. If, however, you're making several of the same requests and would instead like to allow the browser to cache calls, you can specify the function so that a randomly generated one is not created. Inspect the network requests and you'll see (as long as your server is set up to support it) that if you specify the name, you should get 304 - Not Modified (edit: on subsequent requests after the first), while other calls always return 200 OK

If the jsonpCallback is not specified a random callback function will be created and attached to the window object. Something like jQuery1360574548776335413_1776656584447, what is its role? How does it work? Does it have any relation with the success function? Is the error callback never called?

That callback function should contain the code you put in success. The error event is fired if there is an error with the actual request, such as an invalid domain name, 401 server response, and etc.

Upvotes: 1

Related Questions