Created
October 20, 2012 07:05
-
-
Save MrSwitch/3922446 to your computer and use it in GitHub Desktop.
httpRequest, quick and easy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// httpRequest | |
// Make Cross Origin http requests for JSON data. | |
// The first path is url, the second is a callback, as a JSON object. | |
// If XHR CORS is not supported then JSONP is used. "&callback=" is appended to the request URL. | |
// @author Andrew Dodson | |
function httpRequest(url,callback){ | |
// IE10, FF, Chrome | |
if('withCredentials' in new XMLHttpRequest()){ | |
var r = new XMLHttpRequest(); | |
// xhr.responseType = "json"; // is not supported in any of the vendors yet. | |
r.onload = function(e){ | |
callback(r.responseText?JSON.parse(r.responseText):{error:{message:"Could not get resource"}}); | |
}; | |
r.open('GET', url); | |
r.send( null ); | |
} | |
else{ | |
// JSONP | |
// Make the anonymous function. not anonymous | |
var callback_name = 'jsonp_' + parseInt(Math.random()*1e10); | |
window[callback_name] = callback; | |
// find a place to insert the script tag | |
var sibling = document.getElementsByTagName('script')[0]; | |
// Create the script tag | |
var script = document.createElement('script'); | |
// Update the path with the callback name | |
script.src = (url+"&callback="+callback_name); | |
// Append | |
sibling.parentNode.insertBefore(script,sibling); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment