Ajax实现无刷新任务进度条 (webform)

前端之家收集整理的这篇文章主要介绍了Ajax实现无刷新任务进度条 (webform)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

上面方法优点在于session保存的线程运算类对象页面刷新后方便获得运算对象

而用Session["work"]=w可能因为很多原因而丢失

用window.setTimeout('location.href=location.href',1000)刷新,但页面元素多的情况下页面不断刷新很有可能进度条一直不能显示

下面是在上面的基础上去掉了用session保存线程类而是用在线程类中用静态变量保存当前任务量百分比此方法将带来线程同步问题、使用Ajax实现进度条局部刷新

效果如下面:

前台用Timer控件实时局部刷新。

  1. <head runat="server">
  2. <title></title>
  3. <style type="text/css">
  4. .lblTxtCenter
  5. {
  6. text-align: center;
  7. }
  8. </style>
  9. </head>
  10. <body>
  11. <form id="form1" runat="server">
  12. <div>
  13. <asp:ScriptManager ID="ScriptManager1" runat="server">
  14. </asp:ScriptManager>
  15. <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  16. <ContentTemplate>
  17. <div style='width: 200px; background-color: Silver; height: 20px;'>
  18. <asp:Label runat="server" ID="lbl" CssClass="lblTxtCenter"></asp:Label></div>
  19. <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick" Enabled="false">
  20. </asp:Timer>
  21. <br />
  22. <asp:Button ID="Button1" runat="server" Text="开始运算" OnClick="Button1_Click" />
  23. </ContentTemplate>
  24. </asp:UpdatePanel>
  25. </div>
  26. </form>
  27. </body>


  1. 后台代码
  2. protected void Button1_Click(object sender,EventArgs e)
  3. {
  4. //线程计算类
  5. ThreadClass cl = new ThreadClass();
  6. cl.begin();
  7. Timer1.Enabled = true;
  8. }
  9. protected void Timer1_Tick(object sender,EventArgs e)
  10. {
  11.  
  12. if (ThreadClass.present <= 100)
  13. {
  14. Button1.Enabled = false;
  15. lbl.Text = ThreadClass.present.ToString() + "%";
  16. lbl.BackColor = System.Drawing.Color.Red;
  17. lbl.Width = ThreadClass.present * 2;
  18. }
  19. if (ThreadClass.present == 100)
  20. {
  21. ThreadClass.present = 0;
  22. Button1.Enabled = true;
  23. Timer1.Enabled = false;
  24. }
  25. }

  1. 1 public class ThreadClass
  2. 2 {
  3. 3 public static int present;
  4. 4 public ThreadClass()
  5. 5 {
  6. 6
  7. 7 }
  8. 8 public void begin()
  9. 9 {
  10. 10 if (present == 0)
  11. 11 {
  12. 12 lock (this)
  13. 13 {
  14. 14 Thread tr = new Thread(new ThreadStart(() =>
  15. 15 {
  16. 16 for (int i = 0; i <= 1000; i++)
  17. 17 {
  18. 18 present = 100 * i / 1000;//计算已完成的百分比
  19. 19 Thread.Sleep(10);
  20. 20 }
  21. 21 }));
  22. 22 tr.IsBackground = true;
  23. 23 tr.Start();
  24. 24 }
  25. 25 }
  26. 26 }
  27. 27 }




猜你在找的Ajax相关文章