python (bottle) - 异步响应 - 处理客户端 (javascript)
python (bottle) - asynchronous respose - handling client-side (javascript)
我在 Bottle 文档中找到了 this 异步响应示例。
这里是稍微修改过的代码:
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:
中所述
If you run this script and point your browser to
http://localhost:8080/stream, you should see START, MIDDLE, and END
show up one by one (rather than waiting 8 seconds to see them all at
once).
我想知道如何通过 AJAX 请求中的 Javascript 处理此问题,特别是 JQuery,以便按顺序显示消息。
有什么帮助吗?
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()
This works in all modern browsers, including IE 10. W3C specification here.
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.
来源:How to write javascript in client side to receive and parse `chunked` response in time?
我在 Bottle 文档中找到了 this 异步响应示例。
这里是稍微修改过的代码:
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:
中所述If you run this script and point your browser to http://localhost:8080/stream, you should see START, MIDDLE, and END show up one by one (rather than waiting 8 seconds to see them all at once).
我想知道如何通过 AJAX 请求中的 Javascript 处理此问题,特别是 JQuery,以便按顺序显示消息。
有什么帮助吗?
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()
This works in all modern browsers, including IE 10. W3C specification here.
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.
来源:How to write javascript in client side to receive and parse `chunked` response in time?