javascript - python (bottle) - 异步响应 - 处理客户端 (javascript)

标签 javascript python ajax asynchronous bottle

我找到了this Bottle 文档中有关异步响应的示例。

这里是稍微修改过的代码:

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')

从浏览器调用此 View 的工作方式如 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?

关于javascript - python (bottle) - 异步响应 - 处理客户端 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43171627/

相关文章:

javascript - React-Native使用三元运算符动态改变 View 高度

javascript - 等待ajax请求完成

javascript - stackoverflow技术推送消息?

javascript - 如何将十六进制字符串转换为字节数组,以及十六进制字符串中的字节数组?

javascript - 为什么在几乎没有阻塞操作的情况下,事件循环从 JavaScript 开始就存在

python - 在 python 中使用隐式欧拉求解 PDE - 输出不正确

python - ZeroMQ 管道模式

python - 使用 numpy vectorize 时如何避免大量额外的内存消耗?

javascript - AJAX 无法持续​​工作

javascript - 将对象数组转换为包含对象的数组的最佳方法