我正在编写一个非常简单的演示 Web 应用程序,我似乎无法使用 ajax 将 json 对象从 js 传递到 python>.
我已经尝试了一些来自有类似问题的人的建议,例如使用 .get_json() 而不是 .json,传递对象而不使用JSON.stringify javascript等
知道我在这里遗漏了什么吗?
Javascript
var run_method = function(){
var data1 = {"word":"hello"}
console.log("Before " + data1);
$.ajax({
url : "/examplemethod",
type : "POST",
data : data1//JSON.stringify(data1)
})
.done(function(data){
var data = JSON.parse(data);
console.log(data);
});
}
python
@app.route("/examplemethod", methods=['POST', 'GET'])
def example_method():
global data
if request.method == 'POST':
print request
data = request.json
print "data", data
return "after "+ data["word"]
我尝试过的每个变体都会出现 500 错误,并且
TypeError: 'NoneType' object has no attribute 'getitem'
显然,那是因为数据应该是 dictionary/json,而不是 None。但是如何让它作为字典返回呢?
请您参考如下方法:
因为您没有将 JSON 发送到 flask 应用程序(参见 this 和 this )。您当前的代码会生成标准的 urlencoded 表单帖子。这反过来导致在 request.form
request.form.get('word')
按照上述问答中的指南切换到 json post,以通过 request.json 访问数据。
