2017-04-02 102 views
0

我发现this瓶文档示例重新异步响应。蟒蛇(瓶) - 异步respose - 处理客户端(javascript)

这里是稍微修改了代码:

from gevent import monkey; monkey.patch_all() 

from time import sleep 
from bottle import hook, response, route, run 


@route('/stream') 
def stream(): 
    yield 'START' 
    sleep(3) 
    yield '\nPROGRESS 1' 
    sleep(3) 
    yield '\nPROGRESS 2' 
    sleep(3) 
    yield '\nPROGRESS 3' 
    sleep(3) 
    yield '\nEND' 

run(host='0.0.0.0', port=8080, server='gevent') 

调用从浏览器这一观点的作品在the docs作为解释:

如果您运行此脚本和浏览器指向 http://localhost:8080/stream,你应该看到START,MIDDLE和END 一个接一个地出现(而不是等待8秒才能看到它们全部在 一次)。

我想知道如何通过AJAX请求中的Javascript处理这个问题,特别是使用JQuery,以便按顺序显示消息。

对此有何帮助?

回答

1

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

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

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

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

来源:How to write javascript in client side to receive and parse `chunked` response in time?