joris

JSONP Library

Sep 16th, 2012
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. * Lightweight JSONP fetcher
  3. * Copyright 2010-2012 Erik Karlsson. All rights reserved.
  4. * BSD licensed
  5. */
  6.  
  7.  
  8. /*
  9. * Usage:
  10. *
  11. * JSONP.get( 'someUrl.php', {param1:'123', param2:'456'}, function(data){
  12. *   //do something with data, which is the JSON object you should retrieve from someUrl.php
  13. * });
  14. */
  15. var JSONP = (function(){
  16.     var counter = 0, head, query, key, window = this, config = {};
  17.     function load(url) {
  18.         var script = document.createElement('script'),
  19.             done = false;
  20.         script.src = url;
  21.         script.async = true;
  22.  
  23.         script.onload = script.onreadystatechange = function() {
  24.             if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
  25.                 done = true;
  26.                 script.onload = script.onreadystatechange = null;
  27.                 if ( script && script.parentNode ) {
  28.                     script.parentNode.removeChild( script );
  29.                 }
  30.             }
  31.         };
  32.         if ( !head ) {
  33.             head = document.getElementsByTagName('head')[0];
  34.         }
  35.         head.appendChild( script );
  36.     }
  37.     function encode(str) {
  38.         return encodeURIComponent(str);
  39.     }
  40.     function jsonp(url, params, callback, callbackName) {
  41.         query = (url||'').indexOf('?') === -1 ? '?' : '&';
  42.         params = params || {};
  43.         for ( key in params ) {
  44.             if ( params.hasOwnProperty(key) ) {
  45.                 query += encode(key) + "=" + encode(params[key]) + "&";
  46.             }
  47.         }
  48.         var jsonp = "json" + (++counter);
  49.         window[ jsonp ] = function(data){
  50.             callback(data);
  51.             try {
  52.                 delete window[ jsonp ];
  53.             } catch (e) {}
  54.             window[ jsonp ] = null;
  55.         };
  56.  
  57.         load(url + query + (callbackName||config['callbackName']||'callback') + '=' + jsonp);
  58.         return jsonp;
  59.     }
  60.     function setDefaults(obj){
  61.         config = obj;
  62.     }
  63.     return {
  64.         get:jsonp,
  65.         init:setDefaults
  66.     };
  67. }());
Advertisement
Add Comment
Please, Sign In to add comment