使用ajax實現簡單的帶百分比進度條


  需求:當進行文件上傳保存等操作時,能在頁面顯示一個帶百分比的進度條,給用戶一個好的交互體驗

 

實現步驟


JSP頁面

1.添加table標簽

<table id="load" width="700" border="0" align="center" bgcolor="#FAFAFA" cellpadding="0" cellspacing="0" bordercolor="#000000" style="border-collapse:collapse;display:none ">
      <tr>
        <td><br><br>
        <table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#287BCE" style="border-collapse:collapse ">
            <tr bgcolor="#F7F7F6">
              <td width="20%" height="100" valign="middle">
                <table align='center' width='500'>
                  <tr>
                   <td colspan='2' align='center' id="progressPersent"><font size="2">
                    正在進行保存,用時較長,請稍后...
                    </font>
                   </td>
                  </tr>
                  <tr>
                    <td id='tdOne' height='25' width=1 bgcolor="blue">&nbsp;</td>
                    <td id='tdTwo' height='25' width=500 bgColor='#999999'>&nbsp;</td>
                  </tr>
                </table>
              </td>
            </tr>
        </table>
        </td>
      </tr>
    </table> 

  這個table標簽要隱藏,進度條執行的時候再顯示。id為tdOne和tdTwo分別為進度條的藍色和灰色區域。

2.添加js代碼

/**添加帶百分比的進度條*/
    var xmlHttp;
    //創建ajax引擎
    function createXMLHttpRequest() {
      if (window.XMLHttpRequest) {
          xmlHttp = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
          try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
          } catch (e1) {
                try {
                  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e2) {
                }
          }
        }
    }
    
    function loading() {
        createXMLHttpRequest();
        clearLoad();
        var url = "elecCommonMsgAction_progressBar.do";
        xmlHttp.open("GET", url, true);
        xmlHttp.onreadystatechange = createCallback;
        xmlHttp.send(null);
    }
    
    function createCallback() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                //每隔1秒鍾執行一次percentServer()方法,直到當前訪問結束
                setTimeout("percentServer()", 1000);
            }
        }
    }
    
    function percentServer() {
        createXMLHttpRequest();
        var url = "elecCommonMsgAction_progressBar.do";
        xmlHttp.open("GET", url, true);
        xmlHttp.onreadystatechange = updateCallback;
        xmlHttp.send(null);
    }
    
    function updateCallback() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                //獲取XML數據中的percent存放的百分比的值
                var percent_complete = xmlHttp.responseXML.getElementsByTagName("percent")[0].firstChild.data;
                var tdOne = document.getElementById("tdOne");
                var progressPersent = document.getElementById("progressPersent");
                //改變藍色區域的寬度
                tdOne.width = percent_complete + "%";
                //將百分比的數值顯示到頁面上
                progressPersent.innerHTML = percent_complete + "%";
                //如果計算獲取的百分比的數值沒有達到100,則繼續調用方法,直到操作結束為止
                if (percent_complete < 100) {
                    setTimeout("percentServer()", 1000);
                }
            }
        }
    } 
    function clearLoad() {
        document.getElementById("load").style.display="";
        document.getElementById("opperate1").style.display="none";
        document.getElementById("opperate2").style.display="none";
    }

  當點擊保存時,執行loading()方法。

 

Action類

progressBar()方法

/**  
    * @throws Exception 
     * @Name: progressBar
    * @Description: 在頁面執行保存后,使用ajax,計算執行的百分比情況,將結果顯示到頁面上
    * @Parameters: 無
    * @Return: ajax如果不需要跳轉頁面,返回null或者NONE
    */
    public String progressBar() throws Exception{
        //從session中獲取操作方法中計算的百分比
        Double percent = (Double) request.getSession().getAttribute("percent");
        String res = "";
        //此時說明操作的業務方法仍然繼續在執行
        if(percent!=null){
            //計算的小數,四舍五入取整
            int percentInt = (int) Math.rint(percent); 
            res = "<percent>" + percentInt + "</percent>";
        }
        //此時說明操作的業務方法已經執行完畢,session中的值已經被清空
        else{
            //存放百分比
            res = "<percent>" + 100 + "</percent>";
        }
        //定義ajax的返回結果是XML的形式
        PrintWriter out = response.getWriter();
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        //存放結果數據,例如:<response><percent>88</percent></response>
        out.println("<response>");
        out.println(res);
        out.println("</response>");
        out.close();
        return null;

    }

save()方法

/**  
    * @Name: save
    * @Description: 保存表單數據到數據庫
    * @Parameters: 無
    * @Return: String:重定向到system/actingIndex.jsp再查詢
    */
    public String save(){
        //模擬:循環保存150次,方便觀察百分比變化
        for(int i=1;i<=150;i++){
            elecCommonMsgService.saveCommonMsg(elecCommonMsg);//保存數據
            request.getSession().setAttribute("percent", (double)i/150*100);
        }
        //線程結束,清空session
        request.getSession().removeAttribute("percent");
        return "save";
    }

  注意:可以在復雜的業務中將代碼段分成點,一個點的進度是占百分之多少,然后存放到Session中,然后通過ajax調用服務從Session中獲取值,返回進度並顯示即可。


 

效果

  輸入數據,點擊【保存】時:

 


 

總結

  帶百分比的進度條,實際上是用ajax在保存中開啟多個線程實現的:

  • 一個線程,執行保存的操作:

    1.將百分比計算出來,放到session中;

    2.在線程結束的時候,將session清空。

  • 另一個線程,從session中獲取百分比的內容:

    1.使用ajax將結果返回並顯示在頁面上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM