Skip to content

Instantly share code, notes, and snippets.

@xwartz
Created November 16, 2015 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xwartz/c4bb3bcc2c005fc7adb1 to your computer and use it in GitHub Desktop.
Save xwartz/c4bb3bcc2c005fc7adb1 to your computer and use it in GitHub Desktop.
'use strict';
let Ajax = {};
Ajax.xhr = () => {
let xhr, versions;
if(typeof XMLHttpRequest !== undefined) {
xhr = new XMLHttpRequest();
} else {
versions = [
'MSXML2.XmlHttp.5.0',
'MSXML2.XmlHttp.4.0',
'MSXML2.XmlHttp.3.0',
'MSXML2.XmlHttp.2.0',
'Microsoft.XmlHttp'
];
for(let i = 0; i < versions.length; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
} catch (e) {
throw e;
}
}
}
return xhr;
};
Ajax.send = (url, method, data, sync) => {
let promise = new Promise((resolve, reject) => {
let xhr = Ajax.xhr();
// withCredentials
xhr.withCredentials = true;
xhr.open(method, url, sync);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
}
if (method === 'POST') {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
xhr.send(data);
});
return promise;
};
Ajax.get = (url, data, callback, sync) => {
let query = [];
for (let key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
}
url += '?' + query.join('&');
Ajax.send(url, 'GET', null, sync).then((res) => {
callback && callback(res);
});
};
Ajax.post = (url, data, callback, sync) => {
let query = [];
for (let key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
}
Ajax.send(url, 'POST', query.join('&'), sync).then((res) => {
callback && callback(res);
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment