/**
* @public
* @return {XMLHttpRequest, ActiveXObject}
* @param {Function} callback
* @param {String} mode
*/
function getXmlHttpRequest(callback, mode) {
var xhr = null;
if (window.XMLHttpRequest !== undefined) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject !== undefined) {
xhr = new ActiveXObject('Msxml2.XMLHTTP.6.0') ||
new ActiveXObject('Msxml2.XMLHTTP.3.0') ||
new ActiveXObject('Microsoft.XMLHTTP');
} else {
throw new Error('Ajax is not supported.');
}
if (xhr !== null && typeof(callback) === 'function') {
var fn = function() {
if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {
switch (mode) {
case 'text':
callback(xhr.responseText);
break;
case 'xml':
callback(xhr.responseXML);
break;
default:
callback();
break;
}
}
}
xhr.onreadystatechange = fn;
}
return xhr;
}
Использовать вот так:
var xhr = getXmlHttpRequest(function(response) {
alert(response);
}, 'text');
xhr.open('GET', 'path/to/your/script.php', true);
xhr.send();
Кроссбраузерность:
Chrome,
Safari,
Firefox,
Opera,
IE5.5-9.0.