Consuming JSONP APIs Vanilla Javascript

//=============================================// // SETTING UP THE FUNCTION // //=============================================// var getJSONP = (function(){ return { send: function(src, options) { var callback_name = options.callbackName || 'foo', on_success = options.onSuccess || function(){}, on_timeout = options.onTimeout || function(){}, timeout = options.timeout || 10; // sec var timeout_trigger = window.setTimeout(function(){ window[callback_name] = function(){}; on_timeout(); }, timeout * 1000); window[callback_name] = function(data){ window.clearTimeout(timeout_trigger); on_success(data); } var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = src; document.getElementsByTagName('head')[0].appendChild(script); } }; })(); //=============================================// // CONSUMING EXAMPLE API: WIKIPEDIA RANDOM // //=============================================// getJSONP.send('http://en.wikipedia.org/w/api.php?grnnamespace=0&format=json&callback=?&action=query&generator=random&callback=foo', { onSuccess: function(json){ console.log('success!', json); }, onTimeout: function(){ console.log('timeout!'); }, timeout: 5 });
Version 1: Currently improving it, it works as it is. Use this function to retrieve JSON data from a site that uses JSONP.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.