How to get AJAX posted JSON in flask?
本问题已经有最佳答案,请猛点这里访问。
我按照这个烧瓶教程学习如何在Python中构建应用程序。
本教程(接近结尾)讨论了如何在Python中获取Ajax发布的JSON,如下所示:
HTML代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"> <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(); } This will send data using AJAX to Python:<br /><br /> Click Me |
python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | `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']) + ' ' return result if __name__ == '__main__': # run! app.run()` |
号
当我运行脚本并在浏览器中单击"单击我"按钮时,当我在浏览器中检查响应时,会得到"500内部服务器错误"。如果我打印数据变量,它将在单击事件的终端中不打印任何数据变量。我尝试了在python脚本中使用get-json(forced=true)和在html文件中字符串化cars-json的注释中给出的建议,但没有成功。
看起来您没有指定post请求的内容类型。请看官方文档中的内容:
By default this function will return None if the mimetype is not
application/json but this can be overridden by the force parameter.
号
您还需要将cars对象序列化为json对象。
你可以这样做:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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(); } |