2012-11-01 05:16:07 +08:00
|
|
|
/**
|
|
|
|
* ajax
|
|
|
|
* Utility to perform ajax get and post requests. Supported browsers:
|
|
|
|
* Chrome, Firefox, Opera, Safari, Internet Explorer 7+.
|
|
|
|
*/
|
|
|
|
var ajax = (function () {
|
2012-11-21 21:09:21 +08:00
|
|
|
function fetch (method, url, body, headers, callback) {
|
2012-11-01 05:16:07 +08:00
|
|
|
try {
|
|
|
|
var xhr = new XMLHttpRequest();
|
|
|
|
xhr.onreadystatechange = function() {
|
|
|
|
if (xhr.readyState == 4) {
|
|
|
|
callback(xhr.responseText, xhr.status);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
xhr.open(method, url, true);
|
2012-11-21 21:09:21 +08:00
|
|
|
if (headers) {
|
|
|
|
for (var name in headers) {
|
|
|
|
if (headers.hasOwnProperty(name)) {
|
|
|
|
xhr.setRequestHeader(name, headers[name]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2012-11-01 05:16:07 +08:00
|
|
|
xhr.send(body);
|
|
|
|
}
|
|
|
|
catch (err) {
|
|
|
|
callback(err, 0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-11-21 21:09:21 +08:00
|
|
|
function get (url, headers, callback) {
|
|
|
|
fetch('GET', url, null, headers, callback);
|
2012-11-01 05:16:07 +08:00
|
|
|
}
|
|
|
|
|
2012-11-21 21:09:21 +08:00
|
|
|
function post (url, body, headers, callback) {
|
|
|
|
fetch('POST', url, body, headers, callback)
|
2012-11-01 05:16:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
'fetch': fetch,
|
|
|
|
'get': get,
|
|
|
|
'post': post
|
|
|
|
}
|
|
|
|
})();
|