Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

jsonp.js

By: a guest on Apr 22nd, 2012  |  syntax: JavaScript  |  size: 1.94 KB  |  views: 4,055  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // jsonp.js
  2. //
  3. // for using jsonp - it dynamically generates and injects script tags for
  4. // JSONP requests.
  5. //
  6. // Tue, 28 Feb 2012  09:45
  7. //
  8.  
  9.  
  10. (function(globalContext) {
  11.   // "Static" script ID counter
  12.   var scriptTagCounter = 1, head;
  13.  
  14.   function invokeJsonp(fullUrl, cacheOk) {
  15.     var c = cacheOk || true; // false  ... default
  16.     script = buildScriptTag(fullUrl, c);
  17.  
  18.     if (typeof head != 'object') {
  19.       head = document.getElementsByTagName("head").item(0);
  20.     }
  21.     head.appendChild(script);
  22.     return script;
  23.   }
  24.  
  25.   function removeTag(tag)  {
  26.     if (typeof head != 'object') {
  27.       head = document.getElementsByTagName("head").item(0);
  28.     }
  29.     head.removeChild(script);
  30.   }
  31.  
  32.   function buildScriptTag(url, cacheOk)  {
  33.     // Create the script tag
  34.     var element = document.createElement("script"),
  35.       additionalQueryParams, conjunction,
  36.       actualUrl = url,
  37.       elementId = 'jsonp-script-' + scriptTagCounter++;
  38.  
  39.     if (!cacheOk) {
  40.       additionalQueryParams = '_=' + (new Date()).getTime();
  41.       conjunction = (url.indexOf('?') == -1) ? '?' : '&';
  42.       actualUrl = url + conjunction + additionalQueryParams;
  43.     }
  44.  
  45.     // Set attributes on the script element
  46.     element.setAttribute("type", "text/javascript");
  47.     element.setAttribute("src", actualUrl);
  48.     element.setAttribute("id", elementId);
  49.     return element;
  50.   }
  51.  
  52.   globalContext.Jsonp = {invoke : invokeJsonp, removeTag: removeTag};
  53.  
  54. }(this));
  55.  
  56.  
  57. // example usage:
  58. //
  59. //  var scr1;
  60. //
  61. //  function cbFunc(data) {
  62. //    // This is a jsonp callback. It gets invoked when the
  63. //    // injected script tag gets executed by the browser.
  64. //    if (data === null) { return; }
  65. //    populateSelect(data.names, s3);
  66. //    Jsonp.removeTag(scr1);
  67. //  }
  68. //
  69. //  function retrieveChildNames(geonameId, cbName) {
  70. //    var restUrl = 'http://api.example.com/children/187/alpha?cb=cbFunc';
  71. //    scr1 = Jsonp.invoke(restUrl);
  72. //  }
  73. //