Asp.net基於ajax和jquery-ui實現進度條
阿新 • • 發佈:2020-12-04
前臺用ajax不停進行查詢,直到任務完成。進度條用的是jquery-ui。後臺用一般處理程式處理相應,進度資訊儲存在HttpContext.Application中。
程式碼作為簡單示例,實際應用時應對資源釋放、防止多執行緒混亂等做進一步控制。
效果圖:
程式碼:
前臺:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="Scripts/jquery-2.1.4.min.js"></script> <script src="Scripts/jquery-ui-1.11.4.min.js"></script> <link href="Content/themes/base/all.css" rel="external nofollow" rel="stylesheet" /> <script type="text/javascript"> function GetProgress() { $.ajax({ url: "/Handler1.ashx",type: "POST",data: { "RequestType": "AjaxRequest","Method": "GetProgress" },success: function (data) { if (data != -1) { //工作沒有結束,繼續查詢進度 setTimeout(GetProgress,100); $("#progress").html(data); $("#progressbar").progressbar({ value: parseInt(data) }); } else { //工作完成 $("#progress").html("done"); $("#progressbar").progressbar({ value: 100 }); $("#btn1").attr("disabled",false); } } }); } function DoWork() { //禁用按鈕 $("#btn1").attr("disabled",true); $.ajax({ url: "/Handler1.ashx","Method": "DoWork" } }); //開始查詢進度 setTimeout(GetProgress,500); } </script> </head> <body> <div> <input type="button" id="btn1" value="開始" onclick="DoWork();" /> <label id="progress"></label> <div id="progressbar"></div> </div> </body> </html>
後臺:
// 2015年12月16日 09:53:11 // David Huang // 進度條示例 namespace ProgressTest { using System; using System.Threading; using System.Web; /// <summary> /// Handler1 的摘要說明 /// </summary> public class Handler1 : IHttpHandler { // context private HttpContext context; public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { this.context = context; if (context.Request["RequestType"] == "AjaxRequest") { if (context.Request["Method"] == "GetProgress") { context.Response.Clear(); context.Response.Write(this.GetProgress()); context.Response.End(); } else { this.DoWork(); } } } /// <summary> /// 開始工作 /// </summary> private void DoWork() { for (int i = 0; i < 100; i++) { // 記錄進度 // 實際應用中需要進一步控制(利用使用者資訊、cookies等),防止併發造成混亂 this.context.Application["progress"] = i + 1; Random r = new Random(); Thread.Sleep(r.Next(10,100)); } // 完成後釋放資源 this.context.Application["progress"] = null; } /// <summary> /// 查詢進度 /// </summary> /// <returns>進度</returns> private int GetProgress() { if (this.context.Application["progress"] != null) { return (int)this.context.Application["progress"]; } else { return -1; } } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。