Created
November 26, 2013 05:20
-
-
Save Daniel15/7653825 to your computer and use it in GitHub Desktop.
Basic AJAX loading
This file contains hidden or 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
/** | |
* Does an AJAX load of the specified URL | |
* | |
* @param {String} url URL to load | |
* @param {Object} data Hash of data to send in querystring | |
* @param {Function} callback Function to call once request returns | |
*/ | |
function load(url, data, callback) { | |
if (data) { | |
var params = Object.keys(data) | |
.map(function(key) { | |
return key + '=' + encodeURIComponent(data[key]); | |
}) | |
.join('&'); | |
url += '?' + params; | |
} | |
var xhr = new XMLHttpRequest(); | |
xhr.open('get', url, true); | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === 4) { | |
// Try parse as JSON | |
var data; | |
try { | |
data = JSON.parse(xhr.responseText); | |
} catch (ex) { | |
data = null; | |
} | |
// Check for success | |
if (xhr.status != 200 || !data || !data.success) { | |
var message = (data && data.message) || xhr.responseText; | |
alert('Something broke with the request: ' + message); | |
return; | |
} | |
callback(data); | |
} | |
} | |
xhr.send(); | |
return xhr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment