Skip to content

Instantly share code, notes, and snippets.

@skhatri
Last active September 26, 2017 08:14
Show Gist options
  • Save skhatri/5532408 to your computer and use it in GitHub Desktop.
Save skhatri/5532408 to your computer and use it in GitHub Desktop.
simple ajax - cors request, jsonp, xmlhttprequest
function Ajax() {
}
Ajax.prototype.jsonpHandler = function (url, callback) {
var scripturl = url + ((url.indexOf("?") !== -1) ? "&" : "?") + "callback=" + callback;
document.write('<script src="' + scripturl + '"></script>');
return scripturl;
};
Ajax.prototype.request = function (method, url, fallback, options) {
var self = this, options = options || {}, sf = options.success, ef = options.error, params = options.params;
if (options.jsonp) {
return self.jsonpHandler(url, options.jsonpCallback);
}
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
if (fallback === true) {
xhr.open(method, url, true);
} else {
xhr = null;
return xhr;
}
}
xhr.onreadystatechange = function (event) {
if (this.readyState === 4) {
if (this.status === 200 && sf) {
sf(this.responseText);
} else {
ef("Not OK. " + this.statusText);
}
}
};
xhr.onerror = function (data) {
if (ef) {
ef("ajax error " + this.statusText);
}
};
try {
if (params) {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
} else {
xhr.send();
}
} catch (e) {
if (ef) {
ef("error " + e.name + ": " + e.message);
}
}
return xhr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment