function createXMLHttpRequest() {
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
if(request.overrideMimeType) {
request.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject) {
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP',
'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++) {
try {
request = new ActiveXObject(versions[i]);
if(request) {
return request;
}
} catch(e) {}
}
}
return request;
}
function ajax(xmlhttp,_method, _url, _param, _callback) {
if (typeof xmlhttp == 'undefined') return;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
_callback(xmlhttp);
}
}
xmlhttp.open(_method, _url, true);
if (_method == "POST") {
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length", _param.length);
xmlhttp.send(_param);
}
else {
xmlhttp.send(null);
}
}
//使用举例
var xmlhttp = createXMLHttpRequest();
var t1; //用来作超时处理
function adduserok(request) {
alert(request.responseText);
if (t1) clearTimeout(t1);
}
function connecttoFail() {
if (xmlhttp) xmlhttp.abort();
alert ('Time out');
}
if (xmlhttp) {
ajax(xmlhttp,"POST", "http://10.1.2.187/adduser.cgi","act=do&user=abc",adduserok);
t1 = setTimeout(connecttoFail,30000);
}
else {
alert ("Init xmlhttprequest fail");
}