Skip to content

Instantly share code, notes, and snippets.

@MatthewBarker
Created February 18, 2015 14:07
Show Gist options
  • Save MatthewBarker/16057d9745a7077ee95c to your computer and use it in GitHub Desktop.
Save MatthewBarker/16057d9745a7077ee95c to your computer and use it in GitHub Desktop.
JSONP request function
/*jslint browser: true*/
/*global define, exports, module*/
/**
A module that makes jsonp requests.
@module jsonp
@author Matt Barker
*/
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD
define([], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory();
} else {
// Browser global
window.jsonp = factory();
}
}(function () {
'use strict';
var id = 0;
/**
This callback type is used to handle JSONP responses.
@callback requestCallback
@param {Object} data - JSON response
*/
/**
Make a JSONP request.
@param {string} url - Address to send the request to
@param {requestCallback} callback - Function to pass the returned JSON data to
@param {Object} [context] - Context for the callback function
@example
var url = 'http://en.wikipedia.org/w/api.php?format=json&action=query&list=geosearch&gsradius=1000&gscoord=52.42350%7C-1.71347&callback=';
function callback(data) {
console.log(data);
}
jsonp(url, callback);
*/
function jsonp(url, callback, context) {
id += 1;
var wrapper = 'JSONP_request' + id,
script = document.body.appendChild(document.createElement('script'));
script.src = url + wrapper;
window[wrapper] = function () {
window[wrapper] = callback.apply(context || window, arguments);
document.body.removeChild(script);
};
}
return jsonp;
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment