如何在客户端编写javascript以及时接收和解析`chunked`响应? [英] How to write javascript in client side to receive and parse `chunked` response in time?

查看:41
本文介绍了如何在客户端编写javascript以及时接收和解析`chunked`响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用播放框架来生成分块响应.代码是:

I'm using play framework, to generate chunked response. The code is:

class Test extends Controller {
    public static void chunk() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            String data = repeat("" + i, 1000);
            response.writeChunk(data);
            Thread.sleep(1000);
        }
    }
}

当我使用浏览器访问http://localhost:9000/test/chunk时,我可以看到显示的数据每秒增加.但是,当我编写一个 javascript 函数来接收和处理数据时,发现它会阻塞直到接收到所有数据.

When I use browser to visit http://localhost:9000/test/chunk, I can see the data displayed increased every second. But, when I write a javascript function to receive and handle the data, found it will block until all data received.

代码是:

$(function(){
    $.ajax(
        "/test/chunked", 
        {
            "success": function(data, textStatus, xhr) {
                alert(textStatus);
            }
        }
    );
});

我可以看到 10 秒后,当收到所有数据时弹出一个消息框.

I can see a message box popped up after 10s, when all the data received.

如何获取流并及时处理数据?

How to get the stream and handle the data in time?

推荐答案

jQuery 不支持,但你可以用普通的 XHR 做到这一点:

jQuery doesn't support that, but you can do that with plain XHR:

var xhr = new XMLHttpRequest()
xhr.open("GET", "/test/chunked", true)
xhr.onprogress = function () {
  console.log("PROGRESS:", xhr.responseText)
}
xhr.send()

这适用于所有现代浏览器,包括 IE 10.W3C 规范 此处.

This works in all modern browsers, including IE 10. W3C specification here.

这里的缺点是 xhr.responseText 包含累积响应.您可以在其上使用子字符串,但更好的主意是使用 responseType 属性并在 ArrayBuffer 上使用 slice.

The downside here is that xhr.responseText contains an accumulated response. You can use substring on it, but a better idea is to use the responseType attribute and use slice on an ArrayBuffer.

这篇关于如何在客户端编写javascript以及时接收和解析`chunked`响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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