gpt4 book ai didi

c# - 如何将后台代码的进度百分比传递给Jquery进度条?

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:57 25 4
gpt4 key购买 nike

我在 asp.net 中有一个后台 worker 。我想传递进度更改的百分比并将其显示在 jquery 进度条中。不幸的是,我发现它只更新一次进度条并且只有进度完成。

查询

    $(document).ready(function() {
$("#progressbar").progressbar();
setTimeout(updateProgress, 100);
});

function updateProgress() {
$.ajax({
type: "POST",
url: "Downloader.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
// Replace the div's content with the page method's return.

$("#progressbar").progressbar("option", "value", msg.d);
}
});
}

下载器.aspx.cs

static BackgroundWorker _bw;
public static int Percent { get; set; }

protected void Button1_Click(object sender, EventArgs e)
{
_bw = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
_bw.DoWork += bw_DoWork;
_bw.ProgressChanged += bw_ProgressChanged;
_bw.RunWorkerCompleted += bw_RunWorkerCompleted;

_bw.RunWorkerAsync("Hello world");
}

void bw_DoWork(object sender, DoWorkEventArgs e)
{

for (int i = 0; i <= 100; i += 20)
{
if (_bw.CancellationPending) { e.Cancel = true; return; }
_bw.ReportProgress(i);
Thread.Sleep(1000);
}
e.Result = 123;
}

void bw_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
percentage.Text = "Complete: " + e.Result; // from DoWork
}

void bw_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
Percent = e.ProgressPercentage;
}

[WebMethod]
public static int GetData()
{
return Percent;
}

一旦 bw_ProgressChanged 检测到任何变化,如何更新 jquery 进度条?

最佳答案

您必须在 ajax success 函数中递归 setTimeout(),直到该过程完成。

这种方法称为 ajax 轮询。

模拟 HTML:

    <asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" />
Percentage:<asp:Label ID="percentage" runat="server"></asp:Label>

客户端脚本:

    $(document).ready(function () {
// TODO: revert the line below in your actual code
//$("#progressbar").progressbar();
setTimeout(updateProgress, 100);
});

function updateProgress() {
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
// TODO: revert the line below in your actual code
//$("#progressbar").progressbar("option", "value", msg.d);
$("#percentage").text(msg.d);
if (msg.d < 100) {
setTimeout(updateProgress, 100);
}
}
});
}

代码隐藏: 没有变化。

关于c# - 如何将后台代码的进度百分比传递给Jquery进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6870008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com