实时处理大量缓慢的传入ajax响应 [英] Handling a big slow incoming ajax response in real time

查看:161
本文介绍了实时处理大量缓慢的传入ajax响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将AJAX请求作为WebApplication的一部分来实现. 服务器端需要很长时间才能完全处理请求,但是它可以很早地输出结果的单个项. 因此,我的目的是让客户端在响应部分到达后立即对其进行渲染,而不要等到响应完成.

I'm trying to implement an AJAX request as part of a WebApplication. The server side needs a long time to process the request completely, but it can output single items of the result very early. So my intention is to have the client side render the parts of the response as soon as they arrive and not wait until the response is complete.

这是我的(简化的)服务器端代码:

Here is my (simplified) server side code:

for (myObj o : db.results()) {
    // some rather slow operations at this place
    JSONObject j = new JSONObject();
    j.put("tag1", o.tag1());
    j.put("tag2", o.tag2());
    System.out.println("Sending partial response: " + j.toString() );
    response.getWriter().write(j.toString());
    response.getWriter().flush();
}

我的客户端jquery请求看起来像这样:

My client side jquery request would look something like this:

$.ajax( {
    type: "GET",
    url: "queryURL",
    dataType: "text",
    success: function (data) {
        alert("received " + data);
    }
});

不幸的是,成功功能仅在响应完成后才执行. 每次调用response.getWriter().write()时,我都找不到执行函数的方法. 有办法吗?

Unfortunately the success-function is only executed once the response is completed. I couldn't find a way to execute a function for each time I call response.getWriter().write(). Is there a way to do that?

推荐答案

尝试实现"AJAX推送"类型的实现可能非常困难.

Trying to implement an "AJAX push" type of implementation can be very difficult.

更简单的实现可能是让您的AJAX调用在服务器上启动该过程,但让服务器将正在执行的结果写入正在执行其操作的某个文件(例如,文本,xml等).您的AJAX成功/完成操作可以按设定的时间间隔(即每5秒一次)读取此文件,直到到达文件结尾为止.

A much simpler implementation of this could be to have your AJAX call start the process on the server, but have the server write the ongoing results to some file (i.e. as text, xml, whatever) as it's doing its thing. Your AJAX success/done could be reading this file at some set interval (i.e. every 5 seconds) until it reaches the end-of-file.

这不是很优雅...但是它很简单并且可以正常工作!

It's not elegant... but it's simple and it works!

这篇关于实时处理大量缓慢的传入ajax响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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