如何将Flask的JSON传递给Javascript [英] How can I pass JSON of flask to Javascript

查看:290
本文介绍了如何将Flask的JSON传递给Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an index page, which contains a form, fill in the form and sends the data to a URL, which captures the input, and does the search in the database, returning a JSON. How do I get this JSON, and put it on another HTML page using Javascript?

索引形式:

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

我的返回JSON的函数:

My function that returns JSON:

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

提交表单后,

推荐答案

您的HTML页面.我们称之为response.html

Your HTML page after you submit the form. let's call it 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>

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

Your flask function that sends JOSN and redirects to response.html

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

这篇关于如何将Flask的JSON传递给Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆