Skip to content

Instantly share code, notes, and snippets.

Created December 16, 2012 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4303892 to your computer and use it in GitHub Desktop.
Save anonymous/4303892 to your computer and use it in GitHub Desktop.
// Adds one JSONP global (for requireJS module, see JSONP.js)
var JSONP = (function (global) {
// (C) WebReflection Essential - Mit Style
// cleaned up by Brett Zamir for JSLint and avoiding additional globals and need for conventional [?&]callback= in URL)
'use strict';
var id = 0,
ns = 'JSONP',
prefix = '__JSONP__',
document = global.document,
documentElement = document.documentElement;
return function (uri, callback) {
var src = prefix + id++,
script = document.createElement('script'),
JSONPResponse = function () {
try { delete global[ns][src]; } catch(e) { global[ns][src] = null; }
documentElement.removeChild(script);
callback.apply(this, arguments);
};
global[ns][src] = JSONPResponse;
documentElement.insertBefore(
script,
documentElement.lastChild
).src = uri + (uri.indexOf('?') > -1 ? '&' : '?') + 'callback=' + ns + '.' + src;
};
}(this));
/*globals define */
define(function () {
// (C) WebReflection Essential - Mit Style
// cleaned up by Brett Zamir for JSLint and avoiding additional globals and need for conventional [?&]callback= in URL)
'use strict';
var id = 0,
global = this,
ns = 'JSONP',
prefix = '__JSONP__',
document = global.document,
documentElement = document.documentElement;
return function (uri, callback) {
var src = prefix + id++,
script = document.createElement('script'),
JSONPResponse = function () {
try { delete global[ns][src]; } catch(e) { global[ns][src] = null; }
documentElement.removeChild(script);
callback.apply(this, arguments);
};
global[ns][src] = JSONPResponse;
documentElement.insertBefore(
script,
documentElement.lastChild
).src = uri + (uri.indexOf('?') > -1 ? '&' : '?') + 'callback=' + ns + '.' + src;
};
});
/*globals define */
define(['JSONP'], function MediaWikiJSONP(baseURL, argObj, cb) {
var uri, arg, args = '';
if (!cb) {
cb = argObj;
argObj = null;
}
for (arg in argObj) {
args += '&' + arg + '=' + encodeURIComponent(argObj[arg]);
}
uri = baseURL + '/w/api.php?format=json' + args;
JSONP(uri, cb);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment