简体   繁体   English

通过POST将Flask的JSON返回AJAX

[英]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将用户输入表单发送到Flask,在该表单中进行处理,用于查询中,并将结果作为JSON对象发送回。 AJAX is called upon form submission, and I'm returning the proper query results. 提交表单时会调用AJAX,我将返回正确的查询结果。 But, when the results are returned, the JSON object is printing to the browser window, not maintaining the template format of the original page. 但是,返回结果时,JSON对象将打印到浏览器窗口,而不保留原始页面的模板格式。

views.py 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: 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: 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). 我希望将返回的JSON对象打印到表单下方的屏幕上,但是,返回的数据将直接打印到浏览器窗口中,该窗口不维护'index.html'结构(具有导航栏和表单) )。 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. JavaScript和jQuery / AJAX的新手,所以我很确定自己缺少一些琐碎的东西。

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. 首先,在我没有包含在OP中的一行中,我的jQuery负载很糟糕。 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). 不知道为什么,但是我打开控制台并看到JS错误(使用Chrome,右键单击>>检查>>页面右上角的“控制台”选项卡)。 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: 我从已有的内容中更改了此内容( src="{{ url_for('static', filename="/js/jquery-3.2.1.min.js) }}" ),而是将其作为google托管库加载:

<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: 然后,我的答复被打印在id =“ repsonse”段落中,但内容如下:

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

To actually print the contents of the JSON object, I changed the line 为了实际打印JSON对象的内容,我更改了该行

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

to: 至:

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

That printed my JSON objects with their contents to a paragraph on the page. 那将我的JSON对象及其内容打印到页面上的一段中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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