RSS

JSONP and Ajax

08 Jan

If you are calling to external web service to get JSON data thorough Ajax and if it is in an external domain than your hosted calling application by default web clients will block the Ajax call. Common techniques used for this is JSONP and Cross Origin Resource Sharing(CORS). In JSONP the hack used is if you use tag that requests external javascript file browser will happily download it and server will pad the JSON data in a function call where JSON data included as an argument.
Eg. If you include script tag as following,

Server will respond with data similar to following,
cb([“value1”,”value2”,”value3”]);
So here “cb” can be a function defined in your application domain which can process the response data effectively. This will silently fail if you try to use $.getJSON.
How ever if you are using lot javascript calls to external domain APIs through javascript including this sort of script tags can be cumbersome tasks. However JQuery $.ajax supports cross domain script access where you can define your $.ajax calls like this. This essentially wraps the JSONP hack above mentioned and can be much convenient to use.

$.ajax({
                    url: ‘http://extdomain.com/jsondata.js’
                    cache: true,
                    dataType: 'jsonp',
                    jsonpCallback: 'cb',
                    success: function (data) {
                                            },
                    error: function (jqXHR, textStatus, errorThrown) {
                                            }
                });

Advertisements
 
Leave a comment

Posted by on January 8, 2014 in Javascript

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: