Skip to content

Instantly share code, notes, and snippets.

@gordonglas
Last active August 3, 2019 13:46
Javascript Ajax/Jsonp (no jquery) #js #ajax #jsonp
window.spAjax = (function () {
var that = {};
that.send = function (url, options) {
var onSuccess = options.onSuccess || function () { },
onError = options.onError || function () { },
onComplete = options.onComplete || function () { },
cache = options.cache || false;
if (!cache)
url += (url.indexOf('?') == -1 ? '?' : '&') + '_=' + Math.round((new Date()).getTime() / 1000);
var xhr = new XMLHttpRequest();
xhr.open(options.method || 'GET', url, true);
xhr.timeout = options.timeout || 10000; // millis
xhr.ontimeout = function (e) {
onError('timeout');
onComplete();
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // done
if (xhr.status === 200) { // OK
if (options.dataType === 'json') {
var json = null;
try {
json = JSON.parse(xhr.response);
onSuccess(json);
}
catch (err) {
onError('Failed to parse response as JSON.');
}
}
else {
// this might need more work to support proper responseType:
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType
onSuccess(xhr.response);
}
}
else {
onError((xhr.statusText || '') + ', Status: ' + xhr.status);
}
onComplete();
}
};
xhr.send(method === 'GET' ? null : options.requestData);
};
return that;
})();
window.spJsonp = (function (w, d) {
var that = {};
that.send = function (url, options) {
var callbackName = options.callbackName || 'sp_jsonp_callback',
onSuccess = options.onSuccess || function () { },
onTimeout = options.onTimeout || function () { },
timeout = options.timeout || 10000, // millis
cache = options.cache || false;
if (!cache)
url += (url.indexOf('?') == -1 ? '?' : '&') + '_=' + Math.round((new Date()).getTime() / 1000);
var timeoutObj = w.setTimeout(function () {
w[callbackName] = function () { };
onTimeout();
}, timeout);
w[callbackName] = function (data) {
w.clearTimeout(timeoutObj);
onSuccess(data);
}
var s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url;
d.getElementsByTagName('head')[0].appendChild(s);
};
return that;
})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment