varXHRRequest;
//创建XHR
function createXHR(){
if(typeof XMLHttpRequest != 'undefined'){//IE7+ chrome hotfox and so on
return new XMLHttpRequest();
}else if(typeof ActiveXObject!='undefined'){//IE7-
if(typeof arguments.callee.activeXString!='string'){
var version= ['MSXML2.XMLHTTP6.0','MSXMLHTTP3.0','MSXMLHTTP'];
var len=version.length;
for(vari=0;i<len; i++){
try{
new ActiveXObject(version[i]);
arguments.callee.activeXString=version[i];
}catch(ex){ }
}
}
return new ActiveXObject(arguments.callee.activeXString);
// return new ActiveXObject("Microsoft.XMLHTTP"); //可以直接使用该方法兼容ie5/6
}else{
throw newError("No XHR object avaliable");
}
}
function XHRTools(option) {
if(!XHRRequest){
XHRRequest=createXHR();
}
var params= option.params;
var requestType="";
var url="";
var asyn= option.asyn=="undefined"?true:option.asyn;
var data="";
var dataType=params.dataType =="undefined"?"text":params.dataType;
var contentType= option.contentType=="undefined"?"application/x-www-form-urlencoded": option.contentType;
var timeout= option.timeout!="undefined"?option.timeout:2000;//IE8+
url=addURLParam(requestType,url,"name","milk");
//监测当前活动状态readyState 0:未调用open 1:调用open未调用send 2:调用send未接收到响应 3:接收到部分响应 4:接收到全部响应
//在open之前指定onreadystatechange可保证跨浏览器兼容性
//onload可以替代onreadystatechange事件,表示在接收到完整的响应数据时触发
XHRRequest.onreadystatechange=function() {
if(XHRRequest.readyState==4){
try{
if((XHRRequest.status>=200&&XHRRequest.status<300) ||XHRRequest.status==304){//304表示请求的资源并没有被修改,可以使用浏览器中缓存的版本
alert(XHRRequest.responseText);
}else{
alert("Request was unsucessful: "+XHRRequest.status);
}
}catch(ex){
//当超时时,status可能是4,如果在超时终止请求之后再访问status属性,就会导致错误,所以使用try catch语句
//这里可以处理超时事件
}
}
};
//onprogress事件会接收一个event对象,其target属性是XHR对象。还有额外三个属性:lengthComputable进度信息是否可用,position已接收字节数,totalSizegenju Content-Length响应头部确定的预期字节数。
//在open之前添加。
XHRRequest.onprogress=function(event) {
vardivStatus=document.getElementById("status");
if(event.lengthComputable){//进度信息是否可用
divStatus.innerHTML="Received "+ event.position+" of "+event.totalSize +" bytes";
}
};
XHRRequest.responseType=dataType;
XHRRequest.open(requestType,url,asyn);
//在调用open之后,send之前,设置请求头部信息
XHRRequest.setRequestHeader("Content-Type",contentType);
XHRRequest.setRequestHeader("myHeader","myValue");
XHRRequest.timeout=timeout;
XHRRequest.ontimeout=function() {
alert("Request did not return in time.");
}
XHRRequest.send(data);
};
function addURLParam(requestType, url, key, value) {
url += (url.indexOf("?")== -1)?"?":"&";
if(requestType=='get'){
//get请求的参数名和值要encodeURIComponent
url +=encodeURIComponent(key)+"="+encodeURIComponent(value);
}else{
url += (key)+"="+(value);
}
returnurl;
};