Pet*_*son 31 javascript ajax jquery
有没有办法让一个AJAX请求有多个响应?
例如,如果向服务器发出GET请求需要很长时间才能计算,我怎么能让服务器偶尔发回回复,这些回复会给我一些关于进度的数据?
如果是这样,有人可以发布一个例子,最好用Jquery和服务器可以做到的机制的解释吗?
The*_*ter 23
您可以使用2个ajax调用实现此操作,一个用于运行进程,第二个调用用于定期轮询进度:
在服务器端:
public class ProgressInfo
{
public int Percent {get;set;}
public bool Done {get;set;}
}
public JsonResult DoCalculation(string id)
{
ProgressInfo progress = new ProgressInfo();
if(!string.IsNullOrEmpty(id))
{
Session[id] = progress;
}
//periodicly update progress
progress.Percent++;
}
public JsonResult GetProgress(string id)
{
ProgressInfo progress;
if(string.IsNullOrEmpty(id)
|| (progress = Session[id] as ProgressInfo) == null)
{
return Json(new {
success = false
});
}
if(progress.done)
{
Session.Remove(id);
}
return Json(new {
success = true,
done = progress.done,
percent = progress.Percent
});
}
Run Code Online (Sandbox Code Playgroud)
在客户端:
var progressID = Math.random();
function doCalculation() {
$.post('<%=Url.Action("DoCalcluation")%>/' + progressID);
setTimeout(pollProgress, 1000);
}
function pollProgress() {
$.post('<%=Url.Action("GetProgress")%>/' + progressID, function(response){
if(!response.success) {
alert('Cannot find progress');
return;
}
if(response.done) {
alert('Done!');
} else {
alert('Progress at ' + response.precent + '%');
setTimeout(pollProgress, 1000 /*1 second*/);
}
}, 'json');
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
23574 次 |
最近记录: |