Friday 6 January 2012

Crossdomain Calls Using Jsonp:-

Using the XMLHttpRequest we can't make crossdomain calls.For crossdomain calls in javascript we have to use jsonp approach.

JavaScript File:-
 
 //jquery's document ready event
$(document).ready(function () {
      //url of server page
      var url='http://localhost:2437/CrossDomainServerPage.aspx';

      //callback function name
      var cbfunction='callback';

      //here we are passing the callback function name in the querystring parameter jsonp.     

      call(url + "?jsonp=" + cbfunction);


});
  //function which is used to make the crossdomain request.

 function call(url) {
                 //create the script element
                 var script = document.createElement('script');
              
                 //add the attribute type
                 script.type = 'text/javascript';

                 //add the attribute url
                 script.src = url;
          
                //here we are using the jquery to add the script element to body
                $("body").append(script);
      }

//function which is called from cross domain server page
 function callback(res) {
      //the res is result coming from the cross domain server page
      //alert the result
      alert(res.x + ' : ' + res.y);
}

CrossDomainServerPage.aspx File:-

//the page load event
protected void Page_Load(object sender, EventArgs e){


 //checks whether the jsonp variable is null or not
 if (!string.IsNullOrEmpty(Request.QueryString["jsonp"]))
  {

    //here we get the callbak function name
   

    string Callback = Request.QueryString["jsonp"];   
  
    //call the javascript callback function      
         Response.Write(Callback +"( {\"x\":10 , \"y\":100} );");

    //ends the response
    Response.End();
  }
}



Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

No comments:

Post a Comment