分类:
2010-01-14 10:01:59
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", "","act=do&user=abc",adduserok);
t1 = setTimeout(connecttoFail,30000);
}
else {
alert ("Init xmlhttprequest fail");
}
很简单的两个函数,感觉比起那些原型库来方便多了。也没封装类,那个叫累啊。这么写自己需要什么功能再加就可以了,很容易。初始化对象之所以独立为一个函数是为了要处理超时,使得可以在需要时候取消掉xmlhttp的请求。