添加多个onload事件
functionaddLoadEvent(func){varoldonload=window.onload;if(typeofwindow.onload!=function){window.onload=func;}else{window.onload=function(){oldonload();func();}}}
处理ActiveXObject/XMLHttpRequest问题
//第一种写法,《js高级程序设计》的写法惰性载入技巧functioncreateXHR(){if(typeofXMLHttpRequest!="undefined"){//XMLHttpRequestcreateXHR=function(){returnnewXMLHttpRequest();};}elseif(typeofActiveXObject!="undefined"){//IEActiveXObjectcreateXHR=function(){if(typeofarguments.callee.activeXString!="string"){varversions=["MSXML.XMLHttp.6.0","MSXML.XMLHttp.3.0","MSXML.XMLHttp"],//IEi,len;for(i=0,len=versions.length;ilen;i++){try{newActiveXObject(versions);arguments.callee.activeXString=version;break;}catch(ex){}}}returnnewActiveXObject(arguments.callee.activeXString);};}else{createXHR=function(){thrownewError("fail");}}returncreateXHR();}//第二种写法functioncreateXHR(){if(typeofXMLHttpRequest=="undefined"){XMLHttpRequest=function(){try{returnnewActiveXObject("Msxml.XMLHTTP.6.0");}catch(e){}try{returnnewActiveXObject("Msxml.XMLHTTP.3.0");}catch(e){}try{returnnewActiveXObject("Msxml.XMLHTTP");}catch(e){}returnfalse;}}returnnewXMLHttpRequest();}
请求对象的属性和方法设置
varxhr=createXHR();xhr.onreadystatechange=function(){//firfox引入onlaod,readyState==4时触发,代替onreadystatechangeif(xhr.readyState==4){try{if((xhr.status=00xhr.status)
xhr.status==){alert(xhr.responseText);}else{alert("unsuccessful");}}catch(ex){}}}xhr.onload=function(){if((xhr.status=00xhr.status)
xhr.status==){alert(xhr.responseText);}else{alert("unsuccessful");}}xhr.onprogress=function(event){if(event.lengthComputable){//进度信息是否可用console.log("Received"+event.position+"of"+event.totalSize);}}xhr.onerror=function(){alert("error");}xhr.timeout=;xhr.ontimeout=function(){alert("timeout");}xhr.open("get","example.php",true);xhr.overrideMimeType("text/xml");xhr.send(null);//GET
发送表单数据
varform=document.getElementById("info");xhr.send(serialize(form));//第一种写法xhr.send(newFormData(form));//第二种写法
跨浏览器的CORS
functioncreateCORSRequest(method,url){varxhr=newXMLHttpRequest();if("withCredentials"inxhr){xhr.open(method,url,true);}elseif(typeofXDomainRequest!="undefined"){xhr=newXDomainRequest();xhr.open(method,url);}else{xhr=null;}returnxhr;}varrequest=createCORSRequest("get","