pics/public/js/ajax.js

39 lines
1.0 KiB
JavaScript
Raw Normal View History

function HttpRequest(method, url, payload, callback, context) {
if (!window.XMLHttpRequest) {
return;
}
var request = new XMLHttpRequest();
var async = typeof callback !== 'undefined';
if (async) {
request.onreadystatechange = function() {
if (request.readyState !== 4) {
return;
}
if (request.responseText !== null && request.status === 200) {
var obj = JSON.parse(request.responseText);
if (obj.error) {
alert(obj.error);
return;
}
else {
callback(obj, context);
}
}
};
}
if (method === 'get') {
request.open('GET', url, async);
request.send(null);
} else {
request.open('POST', url, async);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send(payload);
}
return request;
};