gpt4 book ai didi

javascript - 从 flask /python调用Javascript函数

转载 作者:行者123 更新时间:2023-12-03 16:10:34 24 4
gpt4 key购买 nike

我非常了解 Python,但我对 web-stuff 和 JavaScript 不熟悉。我发现了一篇关于 Calling a python function from button on website (Flask) 的帖子.

我想做以下事情:我想在 HTML 表格中添加一个新行。数据将来自 Python。我已经发现刷新站点并不是一个好方法,而是应该使用 JavaScript。假设我有以下 HTML 代码:

<table class="table" id="myTable">
<thead>
<tr>
<th colspan="2">This is a table</th>
</tr>
</thead>
<tbody>
<tr>
<td>entry 1</td>
<td>entry 2</td>
</tr>
</tbody>
</table>
<script src="js/scripts.js"></script>

在 scripts.js 我有以下功能(来自链接的帖子):
function appendRow(table_id) {
var table_ref = document.getElementById(table_id).getElementsByTagName('tbody')[0];
var new_row = table_ref.insertRow(table_ref.rows.length);
var new_cell = new_row.insertCell(0);
var new_text = document.createTextNode('New row');
new_cell.appendChild(new_text);
}

现在忽略函数如何工作/可以优化什么等细节。我真正的问题是:如何从 Python/flask 调用这个函数?

另外:如何将数据(比如 JSON 结构)传递给 JavaScript 函数?

提前谢谢了!

最佳答案

看到这个link您可以使用 ajax 加载表格而无需刷新页面。

您可以使用 flask jsonify 从您的 flask 应用程序中返回 json。看到这个link以下来自 flask 文档的示例

from flask import jsonify
@app.route('/_get_current_user')
def get_current_user():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)

将返回以下 json
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}

关于javascript - 从 flask /python调用Javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46204047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com