简体   繁体   中英

Return JSON from Flask to AJAX via POST

I'm using AJAX to send a user-input form to Flask, where it is processed, used in a query, and the results are sent back as a JSON object. AJAX is called upon form submission, and I'm returning the proper query results. But, when the results are returned, the JSON object is printing to the browser window, not maintaining the template format of the original page.

views.py

@app.route('/table_data', methods=['POST'])
def table_data():
    request_info = request.form
    #Incoming data is processed here and converted into following format:
    data = [{'name': 'bill', 'state': 'CA', 'id': 012345},
            {'name': 'cindy', 'state': 'NY', 'id': 098765}, ...]
    return jsonify(data)

index.html:

<script type="text/javascript" src="{{ url_for('static'), filename='/js/script.js'}}"></script>
<form action="{{ url_for('table_data') }}" class="form-inline" method="post"
        role="form" enctype="application/json">
    <input type="text" class="form-control" id="name" name="name">
    <input type="text" class="form-control" id="state" name="state">
    <input type="text" class="form-control" id="id" name="id">
    <button type='submit' class="btn btn-default">Submit</button>
</form>
<p id="response"></p>

script.js:

$(document).ready(function() {
    $('form').on('submit', function(event) {
        $.ajax({
            url: '/table_data',
            data: $('form').serializeArray(),
            type: 'POST',
            success: function(response) {
                $('#response').text(response);
            }
        })
    });
});

I expect the returned JSON object to be printed to the screen underneath the form, but instead, the data returned is printed directly to the browser window, which doesn't maintain the structure of 'index.html' (which has navbars and a form). I am returned this:

[
    {
        'name': 'bill',
        'state': 'CA',
        'id': 012345
    },
    {
        'name': 'cindy',
        'state': 'NY',
        'id': 098765
    },
    ...
]

Again, this is the proper format, but the data isn't printing to the data

like I want it to. Brand new to JavaScript and jQuery/AJAX, so I'm fairly sure I'm missing something pretty trivial.

SOLUTION :

Turns out I had quite a few issues going on. First, in a line I didn't include in the OP, my load of jQuery was bad. Not sure why, but I opened my console and saw the JS error (using Chrome, right click >> inspect >> "Console" tab at top right of page). I changed this from what I had ( src="{{ url_for('static', filename="/js/jquery-3.2.1.min.js) }}" ) and instead just loaded it as a google hosted library:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

My response was then printed in the paragraph id="repsonse", but as:

[object, Object], [object, Object], ..., [object, Object]

To actually print the contents of the JSON object, I changed the line

$('#response').text(response);

to:

$('#response').text(JSON.stringify(response));

That printed my JSON objects with their contents to a paragraph on the page.

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