Всё оказалось очень просто. Немного подумав пришёл к выводу, что надо было просто добавить
return xhr; сразу после открытия нашего запроса. Вот так:
function _Request(options) {
options = {
type: options.type.toUpperCase() || 'POST',
url: options.url || '',
dataType: options.dataType.toUpperCase() || 'HTML',
param: options.param || '',
success: options.success || function(){},
error: options.error || function(){}
}
var xhr = false;
var rand = Math.floor(Math.random( )*(9999999+1));
if(window.XMLHttpRequest) {
try { xhr = new XMLHttpRequest(); }
catch (e) {}
} else if (window.ActiveXObject) {
try { xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch(e) {}
try { xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch(e) {}
try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e) {}
try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e) {}
}
if(xhr) {
if(options.url != '') {
if(options.type == "GET") {
xhr.open(options.type, options.url+'?'+options.param+'&rnd='+rand, true);
} else if(options.type == "POST") {
xhr.open(options.type, options.url, true);
} else {
return options.error('error');
}
} else {
return options.error('error');
}
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
if(options.dataType == 'HTML') {
return options.success(xhr.responseText);
} else if(options.dataType == 'JSON') {
if(xhr.responseText.replace(/\s+/g, '').length > 0) {
try {
var data = JSON.parse(xhr.responseText);
return options.success(data);
} catch (e) {
return options.error('error');
}
} else {
return options.error('error');
}
} else {
return;
}
} else {
return options.error('error');
}
} else {
return options.error('error');
}
}
if(options.type == "GET") {
xhr.send(null);
return xhr; // ЗДЕСЬ
} else if(options.type == "POST") {
xhr.send(options.param+'&rnd='+rand);
return xhr; // И ЗДЕСЬ
} else {
return options.error('error');
}
} else {
return options.error('error');
}
}
Использование:
var query = _Request({
type: 'GET',
dataType: 'JSON',
url: '/script.php',
param: 'user=stashappy',
success: function(data) {
alert(data.result);
}, error: function(data) {
alert('ERROR');
}
});
Отмена запроса:
query.abort();