我想通过 url_for() 从 Flask html/js 向 python 发送一个变量值。
Python 代码:
@app.route('/video_feed/<device>')
def video_feed(device):
# return the response generated along with the specific media
# type (mime type)
print(device)
try:
return Response(gen(int(device)),mimetype = "multipart/x-mixed-replace; boundary=frame")
except Exception as e:
return Response(gen(device),mimetype = "multipart/x-mixed-replace; boundary=frame")
flask html 文件中所需的内容:
data.value = 0;
image.src = "{{ url_for('video_feed', device=data.value)}}";
但它不起作用,我收到错误:
jinja2.exceptions.UndefinedError: 'data' is undefined
这确实有效,但是我无法在 url_for() 中使用变量 data.value :
image.src = "{{ url_for('video_feed', device=0)}}";
我尝试了几种不同的方法,例如:
image.src = "{{ url_for('video_feed', device=${data.value})}}";
image.src = "{{ url_for('video_feed', device=$data.value)}}";
image.src = "{{ url_for('video_feed', device=%s)}}", data.value;
但似乎没有任何效果。我的 JavaScript 有点生疏。
如有任何帮助,我们将不胜感激!
干杯!
最佳答案
url_for
在页面发送到浏览器之前以及 JavaScript 运行之前,在服务器端展开。
如果您知道页面生成时的编号(device
/data.value
),请通过 render_template()
将其传递到模板.
但是,如果您在页面呈现后才知道该值,则需要构造 img
来自 JavaScript 的元素。
关于javascript - Flask通过url_for()向python发送变量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60424247/