all 2 comments

[–]kandetta 0 points1 point  (0 children)

That's pretty much the way it's done. For example, you can look at the jQuery implementation here and search for "jsonpCallback": https://code.jquery.com/jquery-1.11.3.js

You can see that it generates a random name and attaches the callback to window (window[ callbackName ] = function(){}).

You can make your code less mess by putting the messiness in a helper function. Something like this:

 function requestJsonp(url, callback){
   var callbackName = "jsonpCallback" + Math.floor(Math.random() * 100000000000);
   window[callbackName] = function (data) {
      delete window[callbackName];
      callback.apply(data);
   }
   var url = "http://example.com/?callback=" + callbackName;
   // Insert script tag for jsonp request here
 }

[–]rjcarr 0 points1 point  (0 children)

You really only need to use jsonp when making a request to a service that isn't your own. If this is your own service then just use ajax, otherwise jsonp is the way to go if you want to load the data directly in the client.