Pure Javascript function for JSONP requests


SUBMITTED BY: Guest

DATE: Nov. 5, 2012, 10:10 a.m.

FORMAT: JavaScript

SIZE: 636 Bytes

HITS: 2852

  1. function execJSONP(url, cb) { //url (without "callback=" parameter!) and callback function
  2. var script = document.createElement('script');
  3. script.async = true;
  4. var callb = 'exec'+Math.floor((Math.random()*65535)+1);
  5. window[callb] = function(data) {
  6. var scr = document.getElementById(callb);
  7. scr.parentNode.removeChild(scr);
  8. cb(data);
  9. window[callb] = null;
  10. delete window[callb];
  11. }
  12. var sepchar = (url.indexOf('?') > -1)?'&':'?';
  13. script.src = url+sepchar+'callback='+callb;
  14. script.id = callb;
  15. document.getElementsByTagName('head')[0].appendChild(script);
  16. }

comments powered by Disqus