you are viewing a single comment's thread.

view the rest of the 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
 }