Skip to content

Instantly share code, notes, and snippets.

@Hagith
Created August 20, 2013 08:02
Show Gist options
  • Save Hagith/6278451 to your computer and use it in GitHub Desktop.
Save Hagith/6278451 to your computer and use it in GitHub Desktop.
Simple $.ajax to XMLHttpRequest
jQuery.ajax = function(opts) {
var xhr = new XMLHttpRequest({mozSystem: true});
var method = opts.type || 'GET';
method = method.toUpperCase();
if ('POST' !== method && opts.data) {
opts.url += '?' + jQuery.param(opts.data);
}
xhr.open(method.toUpperCase(), opts.url);
xhr.responseType = opts.dataType || 'json';
xhr.onreadystatechange = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
opts.success(xhr.response);
}
}
xhr.onerror = function () {
opts.error(xhr, 'error');
};
if ('POST' === method && opts.data) {
xhr.send(JSON.stringify(opts.data));
} else {
xhr.send();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment