• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

javascript 搞代码 7年前 (2018-06-13) 187次浏览 已收录 0个评论

文章简介:各个浏览器虽然都支持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);

欢迎大家阅读《支持xhr浏览器:超时设定加载事件进度事…_js,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:支持xhr浏览器:超时设定加载事件进度事_js
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址