Asp.Net jquery progressBar+Ajax 实现无刷新进度条

  这是我的第一篇随笔,学习为主。

  功能:采用jQuery的进度条的插件ProgressBar+Ajax 完成无刷新的实时进度条。

  以发邮件为例:

以下为:Ajax.aspx.cs文件内容---------------------------------------------------

using System.Collections;
usingSystem.Configuration;
usingSystem.Data;
usingSystem.Text;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;

usingPlugNT.Common;
usingPlugNT.Cms.BLL;
usingPlugNT.Cms.Model;
usingPlugNT.Cms.Page;

namespacePlugNT.Cms.Web.Admin
{

    publicpartialclassPre_Ajax:AdminPager
    {
        privateconststring ajax_guid ="ajax_guid";
        protectedvoidPage_Load(object sender,EventArgs e)
        {
            //权限检测
            this.CheckPower();

            string arg =Request["a"]asstring;
            switch(arg)
            {
                case"send_email":
                    SendEmail();
                    break;
                case"get_email_state":
                    GetEmailState();
                    break;
                default:
                    break;
            }
        }

        privatevoidSendEmail()
        {
            string guid = ajax_guid +(Request["guid"]asstring);

            DataTable dt =newArticle().GetList(1,"");
            int dCount =0;
            int tCount = dt.Rows.Count;

            object obj =HttpContext.Current.Cache[guid];
            if(obj !=null)
            {
                HttpContext.Current.Cache.Remove(guid);
            }
            foreach(DataRow dr in dt.Rows)
            {
                dCount++;
                HttpContext.Current.Cache[guid]= dCount.ToString()+","+ tCount.ToString();
            }

        }
        privatevoidGetEmailState()
        {
            string guid = ajax_guid +(Request["guid"]asstring);

            object obj =HttpContext.Current.Cache[guid];
            if(obj !=null)
            {
                string[]arr = obj.ToString().Split(',');
                if(arr.Length==2&& arr[0]==arr[1])
                {
                    HttpContext.Current.Cache.Remove(guid);
                }
                Response.Write(obj.ToString());
            }
            else
            {
                Response.Write("0");
            }
            Response.Flush();
        }

}

}

以下为:SendDemo.aspx 文件内容---------------------------------------------------

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headid="Head1"runat="server">
<title>邮件发送</title>
<linkhref="../css/control.css"rel="stylesheet"type="text/css"media="all"/>
<scriptsrc="../js/jquery-1.2.3.js"type="text/javascript"></script>
<scriptsrc="../js/jquery.progressbar.js"type="text/javascript"></script>
<scripttype="text/javascript"language="javascript">
    $(function(){
        $("#send_progressbar").progressBar({ barImage:'../images/progressbg_green.gif', showText:true});
        $("#iptSend").click(function(){
            $("#send_progressbar").show();
            $.get("./Ajax.aspx?a=send_email&guid="+ $("#hidGuid").val());
            showUpload();
        });
    });
    function showUpload(){
        $.get("./Ajax.aspx?a=get_email_state&guid="+ $("#hidGuid").val(),function(data){
            if(!data){
                return;
            }
            var response = data.split(",");
            if(response.length !=2){
                return;
            }
            var percentage =Math.floor(100* parseInt(response[0])/ parseInt(response[1]));
            $("#send_progressbar").progressBar(percentage);
        });
        setTimeout("showUpload()",750);
    }
</script>
</head>
<body>

          <tablewidth="100%"  border="0"align="center"cellpadding="5"cellspacing="1"bgcolor="#ecf5ff">

            <tr>
              <tdbgcolor="#F4FBFF">&nbsp;</td>
              <tdbgcolor="#F4FBFF">
                <inputid="iptSend"type="button"class="bt"value=" 发送 "/>
                <asp:HiddenFieldID="hidGuid"runat="server"/>
                <spanclass="progressbar"id="send_progressbar"style="display:none">0%</span> 
              </td>
            </tr>
          </table>

</body>
</html>

 

以下为:SendDemo.aspx.cs 文件内容---------------------------------------------------

usingSystem;
usingSystem.Data;
usingSystem.Web;
usingSystem.Web.UI.WebControls;
usingSystem.Text;

usingPlugNT.Cms.Custom;
usingPlugNT.Cms.BLL;
usingPlugNT.Cms.Model;
usingPlugNT.Cms.Page;
namespacePlugNT.Cms.Web.Admin.Pre_Email
{
    publicpartialclassSend:AdminPager
    {
        privateSys bllSys =newSys();
        protectedvoidPage_Load(object sender,EventArgs e)
        {
            //权限检测
            this.CheckPower();
            if(!IsPostBack)
            {
                hidGuid.Value=Guid.NewGuid().ToString();
            }
        }
    }
}

 -------------------------------------------------------------------------------

在计算量比较小时采用setInterval比SetTimeOut更方便一些,如下列:

var progress_key = '512e3b5636065';
 
// this sets up the progress bar
$(document).ready(function() {
    $("#uploadprogressbar").progressBar();
});
 
// fades in the progress bar and starts polling the upload progress after 1.5seconds
function beginUpload() {
    // uses ajax to poll the uploadprogress.php page with the id
    // deserializes the json string, and computes the percentage (integer)
    // update the jQuery progress bar
    // sets a timer for the next poll in 750ms
    $("#uploadprogressbar").fadeIn();
 
    var i = setInterval(function() {
        $.getJSON("demo.php?id=" + progress_key, function(data) {
            if (data == null) {
                clearInterval(i);
                location.reload(true);
                return;
            }
 
            var percentage = Math.floor(100 * parseInt(data.bytes_uploaded) / parseInt(data.bytes_total));
            $("#uploadprogressbar").progressBar(percentage);
        });
    }, 1500);
}

两者的最大区别就是,setTimeout方法不会每隔5秒钟就执行一次showTime函数,它是在每次调用setTimeout后过5秒钟再去执行showTime函数。这意味着如果showTime函数的主体部分需要2秒钟执行完,那么整个函数则要每7秒钟才执行一次。而setInterval却没有被自己所调用的函数所束缚,它只是简单地每隔一定时间就重复执行一次那个函数。

如果要求在每隔一个固定的时间间隔后就精确地执行某动作,那么最好使用setInterval,而如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,那么最好使用setTimeout。

--------------------------------------------------------------------

在回调函数中,可以写进度达到100%时的处理事件
    $("#uploadprogressbar").progressBar({

    max: 2000,

    textFormat: 'fraction',

    callback: function(data) {

        if (data.running_value == data.max) { alert("Callback example: Target reached!"); }

      }

} );
 

静守己心,看淡浮华
原文地址:https://www.cnblogs.com/jianglingli83/p/2936099.html