简体   繁体   中英

How can I pass JSON of flask to Javascript

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 of index:

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

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)))

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>

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)

Use ajax request. This plugin transform the submit button in your HTML form to an Ajax submit

<script> 
    $(document).ready(function() { 
        // bind 'myForm' and provide a simple callback function 
        $('#myForm').ajaxForm(function(response) { 
            var result = jQuery.parseJSON(response);
            $('#someDiv').innerHTML = result.res
        }); 
    }); 
</script>

Use the correct form Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM