支持xhr浏览器:超时设定、加载事件、进度事件

各个浏览器虽然都支持xhr,但仍是有些差别。 

一、超时设定 IE8为xhr对象添加了一个timeout属性,表示请求在等待响应多少毫秒后就终止。再给timeout这只一个数值后,若是在规定的时间内浏览器尚未接收到响应,那么就会触发timeout事件,进而会调用ontimeout事件处理程序。 var xhr = creatXHR(); xhr.onreadystatechange = function(event){ try { if(xhr.readyState ==4){ if((xhr.status >= 200 && xhr.status <300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful:" + xhr.status); } } } catch(ex){ // 假设ontimeout事件处理程序处理 } }; xhr.open("get" , "timeout.php" , true); xhr.timeout = 1000; xhr.ontimeout = function(){ alert("Request did not return in a second."); }; xhr.send(null); 二、加载事件 Firfox在实现XHR对象的某个版本是时,曾致力于简化异步交互模型。因而引入load事件,用以代替readystatechange事件。响应接收完毕后将触发load事件,所以也就没有必要去检查readystate属性了。最终结果为: var xhr = creatXHR(); xhr.onload = function(event){ if((xhr.status >= 200 && xhr.status <300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful:" + xhr.status); } }; xhr.open("get","altevents.php",true); xhr.send(null); 只要浏览器接收到服务器的响应,无论其状态如何,都会触发load事件。而这意味着你必须检查status属性,才能肯定数据是否真的已经可用了。 三、进度事件 Mozilla对XHR的另外一个革新是添加了progress事件,这个时间会在浏览器接受新数据期间周期性的触发,而onprogress事件处理程序会接收到一个event对象,其target属性是XHR对象,但包含着两个额外的属性:position和totalSize。其中position表示已经接受的字节数,totleSize表示根据Content-Length响应头部肯定的预期字节数。 var xhr = creatXHR(); xhr.onload = function(event){ if((xhr.status >= 200 && xhr.status <300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful:" + xhr.status); } }; xhr.onprogress = function(event){ var.divStatus = document.getElementById("status"); divStatus.innerHTML = "Received" + event.position + "of" + event.totalSize +"bytes"; }; xhr.open("get","altevents.php",true); xhr.send(null);
相关文章
相关标签/搜索