javascript - Dynamic JSONP approach -


i wondering whether approach jsonp correct , if not, can change.

my standard jsonp approach:

server

standard ?jsonp=callback parameter

client

  1. call function (example: jsonp(url, callback)) *1
  2. create <script> tag *2
  3. execute script
  4. remove script tag

code
note: wrote of these in stackoverflow editor, code untested
1:

jsonp("http://example.com/sampleapi", function(result) {       //   }); 

2:

var callbackid = 0; var jsonp = function(url, callback) {     var callbackname = 'callback' + callbackid;     // put callback in url     callbackid++;     if (url.indexof('?') != -1) {         url += '&jsonp=' + callbackname;     } else {         url += '?jsonp=' + callbackname;     }      // create callback     window[callbackname] = function(result) {         $('jsonpscriptelement' + callbackid).remove();         callback(result);         window.splice(callbackname);     }      // create actual element (do last thing because of caching)     // assuming prototype.js usage     $$('body')[0].insert(new element('script', {'href': url, 'id': 'jsonpscriptelement' + callbackid})); } 

the problem see this part:

window[callbackname] = function(result) {     $('jsonpscriptelement' + callbackid).remove();     callback(result);     window.splice(callbackname); } 

you making new function every call make. try avoid making generic function still safe use asynchronously. shouldn't hard come something, instance pass sequence number along jsonp call , callback can keep different requests apart.

and yes, jsonp easy :p

additionally can change jsonp function this:

var jsonp = (function() {     var callbackid = 0;     return function (url, callback) {          //.. function body ..     } }()); 

so don't have declare callbackid in global scope


Comments