[英]how can I pass a dictionary from javascript to flask?
我想使用flask和jquery從javascript將字典(button_state)傳遞給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
視圖函數未返回有效響應。 返回類型必須是字符串,元組,Response實例或可調用的WSGI,但這是一個命令。 127.0.0.1--[29 / Oct / 2018 07:53:48]“ POST / signUpUser HTTP / 1.1” 500-
似乎服務器代碼未正確檢索數據,或者JSON.stringify將數據轉換為字符串的方式存在問題。 我已經閱讀了許多其他有相同問題的文章,並嘗試過堆棧溢出的解決方案,但僅收到錯誤400。
我試圖使用另一種方法通過ajax將javascript字典發送到python-flask,並且效果很好。 如果問題是服務器找不到數據 (很有可能),則可以從我描述的方法中獲取啟發(我認為這似乎是最簡單的方法)
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.