如何写javascript在客户端接收并解析`及时chunked`回应? [英] How to write javascript in client side to receive and parse `chunked` response in time?
问题描述
我使用的是发挥框架,产生分块响应。在code是:
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://本地主机:9000 /测试/块
,我可以看到数据显示的增加每一秒。但是,当我写一个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.
在code是:
$(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规范的here 。
This works in all modern browsers, including IE 10. W3C specification here.
这里的缺点是, xhr.responseText
包含一个累计的响应。你可以在上面使用子,但更好的方法是使用 responseType 属性,并使用片
上的 ArrayBuffer
。
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屋!