zoukankan      html  css  js  c++  java
  • 支持xhr浏览器:超时设定、加载事件、进度事件

    各个浏览器虽然都支持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);
  • 相关阅读:
    TCP的核心系列 — SACK和DSACK的实现(一)
    Linux2.6中的Slab层
    UVA 11549 Calculator Conundrum (Floyd判圈算法)
    2013第四届蓝桥杯决赛Java高职高专组题目以及解法答案
    hdu-Common Subsequence
    UVA 10869
    【Struts2学习笔记(3)】至Action注入属性值
    【winows7+android-ndk-r9+Cygwin 】cocos2dx 2.*游戏移植Android平台完全手册
    Ubuntu 14.04 64位字体美化(使用黑文泉驿)
    Android Fragment——详细解释
  • 原文地址:https://www.cnblogs.com/gopark/p/8607141.html
Copyright © 2011-2022 走看看