Created
December 11, 2012 15:15
-
-
Save Lukewh/4259207 to your computer and use it in GitHub Desktop.
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
function getXHR(url, callback) { | |
var xhr = new XMLHttpRequest(); // Creates a new XHR request | |
if (!url) { | |
throw new Error('No URL supplied'); | |
} | |
xhr.open("GET", url, true); // Open the connection | |
xhr.setRequestHeader("Content-type", | |
"text/plain; charset=utf-8;"); | |
xhr.withCredentials = "true"; // This sends cookies through | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === 4) { // If the response has finished downloading | |
if(xhr.status === 200){ // And the content was found | |
try { | |
if (callback) { | |
callback(null, JSON.parse(xhr.responseText)); | |
} | |
} catch(e){ | |
throw new Error('Malformed response'); | |
} | |
} | |
} | |
} | |
xhr.send(); // Makes the request | |
} |
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
"permissions": [ | |
"http://atlas.metabroadcast.com/", | |
"http://*.google.co.uk/" | |
] |
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
function postXHR(url, data, callback) { // Added data to function | |
var xhr = new XMLHttpRequest(); | |
if (!url) { | |
throw new Error('No URL supplied'); | |
} | |
xhr.open("POST", url, true); // Changed "GET" to "POST" | |
xhr.setRequestHeader("Content-type", | |
"text/plain; charset=utf-8;"); | |
xhr.withCredentials = "true"; | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === 4) { | |
if (xhr.status === 200) { | |
try { | |
if (callback) { | |
callback(null, JSON.parse(xhr.responseText)); | |
} | |
} catch(e) { | |
throw new Error('Malformed response'); | |
} | |
} | |
} | |
} | |
if (data) { | |
data = JSON.stringify(data); // Stringify the data Object literal | |
xhr.send(data); // Added the JSON stringified object. | |
} else { | |
xhr.send(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment