【问题标题】:Unable to send an array of objects to flask using JSON & AJAX无法使用 JSON 和 AJAX 将对象数组发送到烧瓶
【发布时间】:2019-10-18 12:27:30
【问题描述】:

当我点击生成时,我得到一个空的 []:

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

这是 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"
            });

    })

这是 Flask 中的代码:


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

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

但是,如果我发送一个只有数字的数组,里面没有对象(例如 [2,3,4,5]),我实际上在我的 python 终端上得到了这个数组。那么我应该为要通过的对象添加什么?

编辑: 当我 jsonify 烧瓶中的输入时,我得到: Response 86 bytes [200 OK]

【问题讨论】:

    标签: javascript arrays json ajax flask


    【解决方案1】:

    这可以通过不依赖于 Jquery 的 fetch API (see supported browsers) 来实现。

    基于另一个useful answer,您可以在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>
    

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

    注意这也处理基于请求方法的逻辑:

    • POST 请求会将 json 负载 (req) 打印到服务器控制台,然后使用 Flask 的 jsonify 函数返回响应。
    • 任何其他请求都将呈现templates/index.html 模板。 (向用户显示带有按钮的 UI)

    当你点击界面中的按钮时,你会在服务器控制台看到这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      相关资源
      最近更新 更多