如何让 javascript 在 Flask 上与 python 一起工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18424758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make javascript work with python on Flask?
提问by Pedro Alves
i'm trying to build a dynamic list on Flask. Everyone who loads the page will see this list and can add or remove items from it. If something is added or removed, everybody receives this update.
我正在尝试在 Flask 上构建一个动态列表。加载页面的每个人都会看到这个列表,并且可以在其中添加或删除项目。如果添加或删除某些内容,每个人都会收到此更新。
I'm using Javascript to do some local processing on the list's items and Python to store it (in a singleton way) on the Flask server.
我正在使用 Javascript 对列表的项目进行一些本地处理,并使用 Python 将它(以单例方式)存储在 Flask 服务器上。
I want to have sure that there is consistency between items on python's list object and what javascript shows on the page, so i think the best option is make it read items from the python's list.
我想确保 python 列表对象上的项目与页面上 javascript 显示的内容之间存在一致性,所以我认为最好的选择是让它从 python 列表中读取项目。
How can i make Javascript read items in this Python's list?
我怎样才能让 Javascript 读取这个 Python 列表中的项目?
采纳答案by blakev
What you're looking for is AJAX. You can use this to query your server without reloading the page in the browser. When the page loads, you should grab a time object (using javascript) then every time someone commits their changes to Flask, record their time object along with the new contents. If the time object < the current, you'll need to compare the difference.
您正在寻找的是 AJAX。您可以使用它来查询您的服务器,而无需在浏览器中重新加载页面。当页面加载时,您应该获取一个时间对象(使用 javascript)然后每次有人将他们的更改提交到 Flask 时,记录他们的时间对象以及新内容。如果时间对象 < 当前,您需要比较差异。
As far as reading items from a python list...you're going to need to figure out how you're returning the data from flask. If I were you, I would use the json module to encode your python data in json objects (similar to dictionaries) then return that to the calling browser; the reason is that json is a javascript native type.
至于从 python 列表中读取项目......你需要弄清楚你是如何从烧瓶中返回数据的。如果我是你,我会使用 json 模块将你的 python 数据编码为 json 对象(类似于字典),然后将其返回给调用浏览器;原因是 json 是 javascript 本机类型。
You could also return a string and parse it on the client side.
您还可以返回一个字符串并在客户端解析它。
Anyway, you can figure that out.
无论如何,你可以弄清楚。