进度条作为反应实时传输数据进度的状态,能够灵活运用还是很重要的。在进度条实现中,我们只需要实时修改进度条style中的width属性就可以反应传输数据的情况。当然width的值直接与 proportion=已传输的数据量/总数据量 挂钩。而proportion就是服务器返回给客户端的一个比例值,计算过程可以在服务器端完成。
【示例】
-
HTML
<html> <head> <meta charset="utf-8"> <title>进度条</title> <script> // 创建XMLHttpRequest对象 // 返回值:XMLHttpRequest对象 function createXHR(){ var XHR = [// 兼容不同浏览器和版本的创建函数数组 function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ]; var xhr = null; //尝试调用函数,如果成功则返回XMLHttpRequest对象,否则继续尝试 for (var i = 0; i < XHR.length; i ++ ){ try{ xhr = XHR[i](); }catch (e){ continue //如果发生异常,则继续下一个函数调用 } break; //如果成功,则中止循环 } return xhr; //返回对象实例 } var xhr = createXHR(); //开始向服务器请求数据 function startRun(){ xhr.onreadystatechange = aginCallBack; document.getElementById("run").disabled=true; //设置按钮不可用 var url = "progress.php"; xhr.open("GET",url,true); xhr.send(null); } //进度条执行函数 function aginCallBack() { if (xhr.readyState == 4) { if (xhr.status == 200) { //status状态正常时 var response = xhr.responseText; //将服务器返回的值赋予response console.log("xhr.responseText=" + response); document.getElementById("progress-bar").innerHTML = response + '%'; document.getElementById("progress-bar").style.width = response + '%'; //将得到的值+‘%’号,然后赋值与进度条style的width属性 if (response < 100) { //应为进度条的最大值也就是100%,所以返回值不能大于100,如果大于100则不再请求,当然服务端返回的最大值也为100 t = setTimeout("startRun()", 1000); //每隔一秒钟就调用一次startRun()函数 } else { //document.getElementById("run").disabled=false; //设置按钮可用 document.getElementById("run").value = "更新完成"; } } } } </script> </head> <body> <div id="progress-bar" style="width:0%; background-color:red;"></div> <input type="button" id="run" value="更新" onclick="startRun();"> </body> </html> -
PHP
//清除缓存 header("Expires: Thu, 01 Jan 1970 00:00:01 GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); //text.txt文件用于记录初始时间 $txt = file_get_contents("text.txt"); $timeone = date("i:s",time()); $timenow = getdate(); if ($txt == "") { //如果text.txt文件空,则将当前时间记录下 file_put_contents("text.txt", $timeone); echo 0; //并向客户端返回0,也就是进度条为0% }else{ $arrtxt = explode(":", $txt); $value1 = $arrtxt[0]*60+$arrtxt[1]; $value2 = $timenow["minutes"]*60+$timenow["seconds"]; $proportion = $value2-$value1; //得到时间差,相当于已完成传输多少数据 if ($proportion >= 100){ //如果时间差大于100,则清空text.txt文档。防止返回给客户端的值大于100 file_put_contents("text.txt",""); } echo $proportion; //返回给客户端的值 }