Cross Domain Json (jsonp) Request

From the ever knowledgeable Wikipedia:

JSONP or “JSON with padding” is a communication technique used in JavaScript. It provides a method to request data from a server in a different domain, something prohibited by typical web browsers because of the same origin policy.

Recently, I had the requirement, whereby I needed to send several calls, via javascript, to a server. The catch was, that I needed the server to return the results of my calls, in the order in which the calls were made. Making the calls synchronous achieved this. Heres how:

(With inspiration from  this AJAX guy)

function getJson(arrayOfIds){

       jsonRequest = createSyncCORSRequest(“get”, host + “/info/get/”+arrayOfIds.join);

     if (jsonRequest) {
          jsonRequest.onloadend = function() {
               if(jsonRequest .status==200){
                    var jsonResponse = $j.parseJSON(jsonRequest.responseText);
                         functionWhichProcessesJsonResponse(jsonResponse );

              }
          };
          jsonRequest.send();
     }
}
function createSyncCORSRequest(method, url) {
     var xhr = null;
     if (typeof XDomainRequest != “undefined”) {
          xhr = new XDomainRequest();
          xhr.open(method, url,false);//false parameter makes it synchronous
          xhr.setRequestHeader(‘accept’, “application/json”);
     } else {
          xhr = new XMLHttpRequest();
          xhr.open(method, url,false);//false parameter makes it synchronous
          xhr.setRequestHeader(‘accept’, “application/json”);
     }
     return xhr;
}

cross-domain-json

Nelson Vivas, impersonating json leaping from one domain to the next.

Advertisements

3 Responses to Cross Domain Json (jsonp) Request

  1. Pingback: Shahzad Sarang gloB's

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: