Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Your HTML page after you submit the form. let's call it response.html

<!DOCTYPE html><html><head><title>hello</title></head><body><pid="test"></p><pid="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"])defreturnOne():
        a = {
        "test": "abcd",
        "test1": "efg"
        }
        return render_template("response.html", a=a)

Solution 2:

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

Post a Comment for "How Can I Pass Json Of Flask To Javascript"