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

http://www.itjxue.com  2015-08-06 23:01  来源:未知  点击次数: 

各个浏览器虽然都支持xhr,但还是有些差异。
1超时设定 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);
2加载事件
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属性,才能确定数据是否真的已经可用了。
3.进度事件
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);

(责任编辑:IT教学网)

更多

推荐Javascript/Ajax文章