【问题标题】:How to get AJAX posted JSON in flask? [duplicate]如何在烧瓶中获取 AJAX 发布的 JSON? [复制]
【发布时间】:2018-05-17 13:04:46
【问题描述】:

我正在关注flask tutorial 以了解如何使用 Python 构建应用程序。

本教程(接近结尾)讲述了如何在 python 中获取 AJAX 发布的 json,如下所示:

HTML 代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
// setup some JSON to use
var cars = [
    { "make":"Porsche", "model":"911S" },
    { "make":"Mercedes-Benz", "model":"220SE" },
    { "make":"Jaguar","model": "Mark VII" }
];

window.onload = function() {
    // setup the button click
    document.getElementById("theButton").onclick = function() {
        doWork()
    };
}

function doWork() {
    // ajax the JSON to the server
    $.post("receiver", cars, function(){

    });
    // stop link reloading the page
 event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<a href="" id="theButton">Click Me</a>

Python 代码:

import sys

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

@app.route('/')
def output():
    # serve index template
    return render_template('index.html')

@app.route('/receiver', methods = ['POST'])
def worker():
    # read json + reply
    data = request.get_json()
    result = ''


    for item in data:
        # loop over every row
        result += str(item['make']) + '\n'

    return result

if __name__ == '__main__':
    # run!
    app.run()`

当我运行脚本并单击浏览器中的“单击我”按钮时,当我检查浏览器中的响应时,我得到了“500 内部服务器错误”。如果我打印数据变量,它会在点击事件的终端中打印出 None 。我尝试了 cmets 中给出的建议,在 python 脚本中使用 get_json(forced=true) 并将 html 文件中的“汽车”json 字符串化,但没有成功。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    看起来你没有指定你的帖子请求的内容类型看看in the official documentation说了什么:

    默认情况下,如果 mimetype 不是,此函数 将返回 None application/json 但这可以被 force 参数覆盖。

    您还需要将您的汽车对象序列化为 json 对象。

    你可以这样做:

    function doWork() {
        // ajax the JSON to the server
        $.ajax({
            type: 'POST',
            url: '/receiver',
            data: JSON.stringify (cars),
            success: function(data) { alert('data: ' + data); },
            contentType: "application/json",
            dataType: 'json'
        });
        // stop link reloading the page
        event.preventDefault();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 2017-04-16
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      相关资源
      最近更新 更多