Thursday, July 31, 2014

JSONP and jQuery

JSONP (JSON with Padding) provides a method to request data from a server with different domain. Typical web browser prohibit cross domain request due to same origin policy. We can do it without jQuery, but jQuery provides the interface to wrap the underneath details.

There are 3 settings in $.ajax about JSONP
1. dataType: 'jsonp',
Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

2. jsonp:
Use this setting to change the default callback name ({jsonp}=xxx)

3. jsonpCallback:
Use this setting to define the callback function name (callback={jsonpCallback})

Sample codes:
$.getJSON('http://example.com/get?jsonp=?', function(data) {
  $("#jsondata").text(JSON.stringify(data));
  console.log(data);
});

$.ajax({
    dataType: 'jsonp',
    url: "http://example.com/get",
    success: function (data) {
        // do stuff with data
    }
});

The code to inject information into the DOM still occurs, as does the creation of a callback function. What jQuery does is it adds script tag to the DOM only until the callback (success function) is done executing. The tag is added to the header. It also adds a function to the window object which is called on return. The URL jQuery constructs looks like http://example.com/get?callback=jsonp123456789.

Security
1. We should avoid serving any sensitive data like password, credit card etc personal data from server side jsonp code.
2. We should also avoid any update logic in jsonp server side code.

Reference

http://api.jquery.com/jQuery.ajax/   
http://infoheap.com/jquery-jsonp-cross-domain-ajax/
http://scottseely.com/2010/09/04/how-jsonp-works-and-some-bits-about-implementing-it-in-wcf/

No comments:

Post a Comment