一直用ajax好长时间了,对其原理也有一些了解,最近由于项目需要,使用ajax异步进度条的效果,就研究了一下,用原生的XMLHttpRequest实现进度条函数,XMLHttpRequest有以下函数可以使用,摘自(https://www.w3.org/TR/progress-events/)
type attribute value |
Description | Times | When |
---|---|---|---|
loadstart |
Progress has begun. | Once. | First. |
progress |
In progress. | Zero or more. | After loadstart has been dispatched. |
error |
Progression failed. | Zero or once. | After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched. |
abort |
Progression is terminated. | Zero or once. | |
load |
Progression is successful. | Zero or once. | |
loadend |
Progress has stopped. | Once. | After one of error , abort , or load has been dispatched. |
进度条函数主要使用progress事件。下面构造一个进度条实现的demo
1、构建页面代码
<div class="progress">
<div id="pros" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="" aria-valuemin="" aria-valuemax="" style="width: 0%;">
</div>
</div>
<button id="trigger_ajax" type="button">请求数据</button>
<script type="text/javascript">
var trigger = document.getElementById("trigger_ajax");
trigger.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.onprogress = function (event) {
console.log(event.lengthComputable);
console.log(event.loaded);
if (event.lengthComputable) {
var loaded = parseInt(event.loaded / event.total * ) + "%";
$('#pros').width(loaded);
$('#pros').text(loaded);
}
}
xhr.open("post", "/Home/aaa", true);
xhr.send(null);
}
</script>
进度条Html代码
2、后台处理接口
[HttpPost]
public void aaa()
{
string result = string.Empty;
for (int i = ; i <= ; i++)
{
result += i.ToString();
int len = result.Length;
Response.Headers.Add("Content-Length", len.ToString());
Response.Headers.Add("Content-Encoding", "UTF-8");
Response.Write(result);
}
}
后台数据处理接口
注意到
Response.Headers.Add("Content-Length", len.ToString());
Response.Headers.Add("Content-Encoding", "UTF-8");
,写出 http 头时候,附加 “Content-Length”和Content-Encoding,这样 JS 端的 progress 事件的 event.lengthComputable 值才会为 true
, event.total 才会在数据传输完毕之前取得值,否则 event.lengthComputable 值会返回 false
, event.total 在数据完成之前值都是0
。