如何将 Flask 的 JSON 传递给 Javascript

Mat*_*ara 0 javascript python flask

我有一个索引页面,其中包含一个表单,填写表单并将数据发送到 URL,该 URL 捕获输入,并在数据库中进行搜索,返回 JSON。如何获取此 JSON,并使用 Javascript 将其放在另一个 HTML 页面上?

索引形式:

<form action="{{ url_for('returnOne') }}", method="GET">
<p>Nome: <input type="text" name="nome" /></p>
<input type="submit" value="Pesquisar">
</form>
Run Code Online (Sandbox Code Playgroud)

我的函数返回 JSON:

@app.route('/userQuery', methods=['GET'])
def returnOne():
    dao = Dao()
    nome = request.args.get('nome')
    return jsonify(json.loads(dao.select(nome)))
Run Code Online (Sandbox Code Playgroud)

Bhu*_*bar 6

提交表单后的 HTML 页面。我们就这样称呼它吧response.html

<!DOCTYPE html>
<html>
<head>
    <title>hello</title>
</head>
<body>
    <p id="test"></p>
    <p id="test1"></p>


    <script>
        var b = JSON.parse('{{ a | tojson | safe}}');
        document.getElementById('test').innerHTML = b.test;
        document.getElementById('test1').innerHTML = b.test1;
        console.log(b);
    </script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

您的烧瓶函数发送JOSN并重定向到response.html

@app.route('/userQuery', methods=["POST", "GET"])
def returnOne():
        a = {
        "test": "abcd",
        "test1": "efg"
        }
        return render_template("response.html", a=a)
Run Code Online (Sandbox Code Playgroud)