我在asp.net中有一个后台工作者。我想传递进度中计入的百分比并将其显示在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);
}
});
}
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进度条?
答案 0 :(得分:2)
您必须在ajax成功函数中递归setTimeout()
,直到该过程完成。
此方法称为ajax-polling。
模拟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);
}
}
});
}
代码背后: 无变化。
答案 1 :(得分:0)
你应该在document.ready中使用setTimeout的setInterval(yourfunctionname,1000)。
$(document).ready(function() {
$("#progressbar").progressbar();
setInterval(updateProgress, 100);
});