如何让AJAX在烧瓶中发布JSON?

时间:2017-12-04 05:30:15

标签: python flask

我正在关注此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>
&#13;
&#13;
&#13;

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()`

当我运行脚本并点击按钮时,点击我&#39;在浏览器中,我得到了“内部服务器错误”#39;当我在浏览器中检查响应时。如果我打印数据变量,它会在click事件的终端中打印出None。我尝试了注释中给出的建议,在python脚本中使用get_json(forced = true)并将&#39; cars&#39; json在html文件中但是徒劳无功。

1 个答案:

答案 0 :(得分:0)

看起来您没有指定帖子请求的内容类型,请看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();
}