我想使用flask和jquery将字典(button_state)从javascript传递到python。 在jQuery方面,我有:
$(".btn#submit").click(function(event){
newdata = JSON.stringify(buttons_state);
console.log("submission button POST attempt: " + newdata)
$.ajax({
url: '/submission',
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: newdata,
processData: false,
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
在服务器端:
@app.route('/submission', methods=['POST'])
def submission():
info = request.get_json(silent=False)
return info
但是我收到错误500:
Traceback (most recent call last):
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 1816, in full_dispatch_request
return self.finalize_request(rv)
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 1831, in finalize_request
response = self.make_response(rv)
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 1982, in make_response
reraise(TypeError, new_error, sys.exc_info()[2])
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/_compat.py", line 34, in reraise
raise value.with_traceback(tb)
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 1974, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/werkzeug/wrappers.py", line 921, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/werkzeug/test.py", line 923, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'dict' object is not callable
view函数未返回有效响应。返回类型必须是字符串,元组,Response实例或可调用的WSGI,但这是一个命令。 127.0.0.1--[29 / Oct / 2018 07:53:48]“ POST / signUpUser HTTP / 1.1” 500-
服务器代码似乎无法正确检索数据,或者JSON.stringify将数据转换为字符串的方式存在问题。我已经读过许多其他有相同问题的文章,并尝试过堆栈溢出的解决方案,但只收到错误400。
答案 0 :(得分:0)
我尝试使用另一种方法通过ajax将javascript字典发送到python-flask,并且效果很好。如果问题是服务器找不到数据(很有可能),您可以从我描述的方法(我认为这似乎是最简单的方法)中汲取灵感
我的配置不同,您可以查看this discussion或this link以获得更多信息。
1。在HTML方面:
分别加载jquery并向我的网站添加动态路径:
<script type=text/javascript src="{{url_for('static', filename='jquery.js') }}"> </script>
<script type=text/javascript>$SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; </script>
2。在Jquery方面:
$(function(){
$('.btn#submit').bind('click', function(){
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
new_dict = JSON.stringify(dict);
$.getJSON($SCRIPT_ROOT + '/_submission', {
dict: new_dict,
},function(data){
alert("Data from flask" + data.new_dict_flask);
});
});
});
3。在烧瓶方面:
@app.route('/_submission')
def submission():
new_dict_flask = request.args.get('dict')
return jsonify(new_dict_flask=new_dict_flask)