jQuery 1.5 and JSONP requests


jQuery 1.5 adds better support for JSONP requests. As you might know, JSONP is a way to avoid the same-origin policy and do cross-domain requests by adding a method call around the JSON data.

Because browsers don’t return data from requests that fail, error handling is tricky compared to normal AJAX requests. There is a workaround by using a timer, which is the way the popular jquery.jsonp plugin solves it.

jQuery 1.5 adds this workaround, so you don’t need this plugin. All other features of the plugin, such as custom callback naming, are possible in jQuery now as well.

Here’s an example:

var req = $.ajax({
    url : url,
    dataType : "jsonp",
    timeout : 10000

req.success(function() {
    console.log('Yes! Success!');

req.error(function() {
    console.log('Oh noes!');

The timeout parameter is essential, because this indicates when a request should be considered ‘failed’. Because of this extra parameter you need to use $.ajax instead of $.getJSON.

The req variable contains the jqXHR object, which can be used to attach multiple callbacks and error handlers.

Add a comment