多重响应AJAX请求 [英] Multiple Response AJAX request

查看:160
本文介绍了多重响应AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法有一个Ajax请求有多个响应?

Is there a way to have one AJAX request with multiple responses?

例如,如果做一个GET请求到服务器,将需要很长的时间来计算,我怎么可能让服务器偶尔会发回的响应这给我讲述了一些进展的数据?

For example, if make a GET request to the server which will take a long time to calculate, how could I have the server occasionally send back responses which give me some data about the progress?

如果是这样,可能会有人发布一个例子,preferably使用jQuery,并通过该服务器可以做它的机理的解释?

If so, could somebody post an example, preferably with Jquery and an explanation of the mechanism through which the server can does it?

推荐答案

您可以在此使用2 AJAX调用,一个运行过程,第二个电话定期轮询进度执行:

You can implement this using 2 ajax calls, one to run the process and a second call to periodically poll the progress:

在服务器端:

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
    });
}

在客户端:

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');
}

这篇关于多重响应AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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