querystring = {
parse: function(str, sep, eq) {
eq = eq || '=';
var obj = {};
if (str) {
var parts = str.split(sep || '&'),
i = 0,
j = parts.length;
while (i < j) {
var temp = parts[i++].split(eq);
if (temp[0] !== '') {
obj[temp[0]] = temp[1] === undefined ? '' : decodeURIComponent(temp[1]);
}
}
}
return obj;
},
stringify: function(obj, sep, eq) {
sep = sep || '&';
eq = eq || '=';
var out = [];
for (var i in obj) {
out.push( i + (obj[i] !== '' ? eq + encodeURIComponent(obj[i]) : '') );
}
return out.join(sep);
}
};
// ...
// ajax.post('handler.php', {a: 'тест'}, {done: function(data) { console.log(data); }});
ajax = new (function(){
/* options = {dataType: 'arraybuffer' || 'blob' || 'document' || 'json' || 'text', done: function(data) {...}, fail: function(code, text) {...} } */
this.request = function(method, url, params, options) {
options = options || {};
var req = new XMLHttpRequest;
req.responseType = options.dataType || '';
if (options.done || options.fail) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status >= 200 && req.status < 300) {
if (options.done) {
options.done(req.response);
}
return;
}
if (options.fail) {
options.fail(req.status, req.statusText);
}
}
}
}
req.open(method, url);
if (method.toLowerCase() == 'post') {
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
params = querystring.stringify(params);
}
req.send(params);
};
this.get = function(url, options) {
this.request('GET', url, null, options);
};
this.post = function(url, params, options) {
this.request('POST', url, params, options);
};
})();