异步操作中,通过jQuery的AJAX ASP.net进度条更新 [英] ASP.net progress bar updated via jQuery ajax during async operation

查看:120
本文介绍了异步操作中,通过jQuery的AJAX ASP.net进度条更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个长时间运行的异步任务的一个简单的HTML进度条。问题是,我试图把火关回发运行一些服务器code和做客户端点击事件的同时,开始了ajax轮询,这是造成在Ajax调用返回错误。这是我的jQuery和HTML code:

I'm trying to set up a simple html progress bar for a long-running async task. The problem is that I'm trying to fire off a postback to run some server code and do a client click event at the same time to start the ajax polling, which is causing an error return in the ajax call. Here's my jQuery and html code:

<%@ Page Language="C#" AsyncTimeout="230" CodeFile="test.aspx.cs" Inherits="test" %>

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>
        "use strict";
        var PROGRESS;
        $(document).ready(function () {
            $.ajaxSetup({
                type: "POST",
                contentType: "application/json",
                data: '{}',
                timeout: 10000,
                converters: {
                    "text json": function (data) {
                        var msg;
                        msg = $.parseJSON(data);
                        return msg.hasOwnProperty('d') ? msg.d : msg;
                    }
                }
            });
            PROGRESS = {
                done: false,
                startProgress: function () {
                    var _progress = this;
                    $.ajax({
                        url: 'test.aspx/getProgress',
                        timeout: 20000,
                        data: '{}',
                        dataType: "json",
                        success: function (data) {
                            var currProgress = data * 100;
                            $("#prog").value = currProgress;
                            if (currProgress > 99)
                                _progress.done = true;
                            else
                                setTimeout("PROGRESS.startProgress()", 5000);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            var s = textStatus == null ? "" : textStatus;
                            s += errorThrown == null ? "" : ", " + errorThrown;
                            alert(s);
                        }
                    });
                }
            };
            $("#body_DoUploadButton").on("click", function (event) {
                //event.preventDefault();
                PROGRESS.startProgress();
            });
        });
    </script>
</head>
<body>
    <asp:Button ID="DoUploadButton" Text="Import file" OnClick="UploadButton_Click" runat="server"></asp:Button>
    <progress id="prog" value="0" max="100"></progress>
</body>

下面是我的codebehind:

Here is my codebehind:

public partial class test : System.Web.UI.Page
{
    delegate void AsyncTaskDelegate();
    AsyncTaskDelegate _dlgt;

    IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object extraData)
    {
        _dlgt = new AsyncTaskDelegate(DoImport);
        IAsyncResult result = _dlgt.BeginInvoke(cb, extraData);
        return result;
    }

    void OnEnd(IAsyncResult ar)
    {
        _dlgt.EndInvoke(ar);
    }

    void OnTimeout(IAsyncResult ar)
    {
        //do something
    }

    [WebMethod(EnableSession = true)]
    public static double getProgress()
    {
        if (HttpContext.Current.Session["pctDone"] == null)
            return 0.0;
        return (double)HttpContext.Current.Session["pctDone"];
    }

    protected void DoImport()
    {
        int i = 10;
        while (i-- > 0)
        {
            System.Threading.Thread.Sleep(5000); //fake some work
            Session["pctDone"] = i / 10.0;
        }
        Session["pctDone"] = 1.0;
    }

    protected void UploadButton_Click(object sender, EventArgs e)
    {
        Session["pctDone"] = 0.0;
        PageAsyncTask task = new PageAsyncTask(new BeginEventHandler(OnBegin), new EndEventHandler(OnEnd),
            new EndEventHandler(OnTimeout), null);
        RegisterAsyncTask(task);
        ExecuteRegisteredAsyncTasks();
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        Server.ScriptTimeout = 240;
    }
}

Apparnetly点击按钮干扰了Ajax调用时回发。如果我的JavaScript函数clickhandler加preventDefault,回发永远不会触发(废话),但所有的Ajax调用的工作,因此至少所有的AJAX code的工作确定。有没有办法有一个按钮,两个回传,所以我的服务器code能运行,并做客户端点击事件,所以我可以开始Ajax调用?我想我在这里拧,我需要做的这一切,没有ASP回传,自那时以来,页面被破坏并重新加载,对吧?

Apparnetly the postback when clicking the button is interfering with the ajax call. If I add a preventDefault in the javascript clickhandler, the postback never fires (duh) but all the ajax calls work, so at least all the ajax code is working ok. Is there a way to have a button both postback, so my server code can run, and do a client click event so I can start the ajax calls? I think I'm screwed here, I need to do this all with no asp postbacks, since then the page is destroyed and reloaded, right?

我敢肯定,我要对此都错了。我想移动这一切为服务思想,我会避开所有回发,也将让AJAX调用一个服务做异步工作,并轮询%的完成了服务,但服务没有实现页面异步所以没有RegisterAsyncTask ()来称呼像您可以在.aspx页面上。

I'm sure I'm going about this all wrong. I tried moving all this to a service thinking I'll avoid all postbacks and just make ajax calls to a service to do the async work and also poll the service for percent done, but services don't implement page async so there's no "RegisterAsyncTask()" to call like you can on an .aspx page.

我也想使用会话状态通信的异步任务和Ajax调用,我不知道这是否会之间完成的百分比的价值,但我想我会尝试。如果失败,我需要一些方法来后台任务和Ajax调用之间进行通信的百分比。

I'm also trying to use the session state to communicate the value of the percent done between the async task and the ajax call, which I have no idea if it will work, but I thought I'd experiment. If it fails I need some way to communicate the percent between the background task and the ajax call.

我读了很多关于如何做到使异步Web服务和使用的BeginXXX由Web服务生成的代理调用等等,但是我也发现有很多人试图做类似我的东西的帖子,使得通过jQuery简单的Ajax调用,以及有没有运气,并没有真正的答案,因为我能找到。

I've read a lot on how to do make async webservices and using the Beginxxx calls etc. in the proxy generated by the webservice, but I also found a lot of posts of people trying to do something similar to me, making simple ajax calls via jQuery, and having no luck and no real answers given that I can find.

因此​​,从一个.aspx页面如何开始一个长期运行的任务,无论是与页面异步或服务,并更新了一个简单的HTML5进度条任务运行?好像这将是简单的,但没有:\

So from an .aspx page how do I start a long-running task either with page async or a service, and update a simple html5 progress bar as the task runs? Seems like that would be simple, but no :\

推荐答案

您缺少只是一个基本出发点。回传你的Ajax调用将无法生存。

You are missing just one basic point. Your ajax calls will not survive a postback.

您不能调用 PROGRESS.startProgress()按钮点击,因为你想在那之后发布的页面立即回。回发会导致你的Ajax调用被终止。

You cannot call PROGRESS.startProgress() on button click, cause you want the page to post back immediately after that. A postback would cause your ajax call to be terminated.

如果你想显示一个进度条,你必须得使用Ajax和不使用回传上传的文件。还有像 uploadify 插件,可以帮助。

If you want to show a progress bar, you must upload the file too using ajax and not by using a postback. There are plugins like uploadify that can help.

这篇关于异步操作中,通过jQuery的AJAX ASP.net进度条更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆