简体   繁体   English

无法使用 JSON 和 AJAX 将对象数组发送到 flask

[英]Unable to send an array of objects to flask using JSON & AJAX

I am getting an empty [ ] when i hit generate:当我点击生成时,我得到一个空的 []:

127.0.0.1 - - [18/Oct/2019 01:04:37] "POST / HTTP/1.1" 200 - [] 127.0.0.1 - - [18/Oct/2019 01:04:37] “POST / HTTP/1.1”200 - []

Here's the array & JSON in JS:这是 JS 中的数组 & JSON:


    var List = [
        { load: "2", location: "3" },
        { load: "2", location: "4" },
        { load: "2", location: "8" },
        ];

    document.querySelector('#generate').addEventListener('click',function() {
        var json_list = JSON.stringify(List)
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/",
            traditional: "true",
            data: json_list,
            dataType: "json"
            });

    })

And here is the code in Flask:这是 Flask 中的代码:


    @app.route('/',methods =['GET','POST'])
    def index():
        req = request.get_json()

        print(req)
        return render_template("index.html")

However, if i send a array of just numbers, no objects inside (eg. [2,3,4,5]) I actually get the array on my python terminal.但是,如果我只发送一个数字数组,内部没有对象(例如 [2,3,4,5]),我实际上在我的 python 终端上得到了数组。 So what should I add for the objects to go through?那么我应该通过什么为对象添加到 go 呢?

Edit: When I jsonify the input in flask i get: Response 86 bytes [200 OK]编辑:当我对 flask 中的输入进行 jsonify 处理时,我得到:响应 86 字节 [200 OK]

This could be achieved with the fetch API ( see supported browsers ) which doesn't depend on Jquery.这可以通过不依赖于 Jquery 的获取 API(请参阅支持的浏览器)来实现。

Based on this other useful answer you could have a template at templates/index.html :基于这个其他有用的答案,您可以在templates/index.html有一个模板:

<html>
<body>
<button type="button" id='generate'>Click Me!</button> 

  <script type='text/javascript'>
    var List = [
      { load: "2", location: "3" },
      { load: "2", location: "4" },
      { load: "2", location: "8" },
      ];

    document.getElementById('generate').addEventListener('click', event => {

    fetch("/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(List)
      }).then(res => {
        console.log("Request complete! response:", res);
      });
    });

  </script>
</body>
</html>

The flask file should look like this: flask 文件应如下所示:

from flask import Flask , request, render_template, jsonify
app = Flask(__name__)

@app.route('/',methods =['GET','POST'])
def index():
    if request.method == 'POST':
        req = request.get_json()
        print(req)
        return jsonify({'status':'success'})

    else:
        return render_template('index.html')

if __name__=='__main__':
    app.run(host='0.0.0.0')

Notice that this also handles logic based on the request method:请注意,这也处理基于请求方法的逻辑:

  • POST request will print the json payload ( req ) to the server console, then return a response using Flask's jsonify function. POST 请求会将 json 有效负载 ( req ) 打印到服务器控制台,然后使用 Flask 的jsonify function 返回响应。
  • Any other request will render the templates/index.html template.任何其他请求都将呈现templates/index.html模板。 (display the UI with buttons to the user) (向用户显示带有按钮的 UI)

When you click the button in the interface, you see this at the server console:当您单击界面中的按钮时,您会在服务器控制台上看到:

[{'load': '2', 'location': '3'}, {'load': '2', 'location': '4'}, {'load': '2', 'location': '8'}]

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

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