简体   繁体   English

如何将字典从javascript传递到flask?

[英]how can I pass a dictionary from javascript to flask?

I want to pass a dictionary (button_state) from javascript to python using flask and jquery. 我想使用flask和jquery从javascript将字典(button_state)传递给python。 On the jquery side, I have: 在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);
        }
    });

});

On the server side: 在服务器端:

@app.route('/submission', methods=['POST'])
def submission():
    info = request.get_json(silent=False)
    return info

But I am getting an Error 500: 但我收到错误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

The view function did not return a valid response. 视图函数未返回有效响应。 The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict. 返回类型必须是字符串,元组,Response实例或可调用的WSGI,但这是一个命令。 127.0.0.1 - - [29/Oct/2018 07:53:48] "POST /signUpUser HTTP/1.1" 500 - 127.0.0.1--[29 / Oct / 2018 07:53:48]“ POST / signUpUser HTTP / 1.1” 500-

It seems that the server code is not correctly retrieving the data or that there is a problem with the way that the data was converted to a string by JSON.stringify. 似乎服务器代码未正确检索数据,或者JSON.stringify将数据转换为字符串的方式存在问题。 I have read many others with the same problem, and have tried the solutions on stack overflow, but only get Error 400. 我已经阅读了许多其他有相同问题的文章,并尝试过堆栈溢出的解决方案,但仅收到错误400。

I tried to send a javascript dictionary to python-flask via ajax, using another approach and it works perfectly. 我试图使用另一种方法通过ajax将javascript字典发送到python-flask,并且效果很好。 In case the problem is that the server does not find the data (it is most likely), you can take inspiration from the approach that I describe (which seems the simplest in my opinion) 如果问题是服务器找不到数据 (很有可能),则可以从我描述的方法中获取启发(我认为这似乎是最简单的方法)

My configuration is different, you can see this discussion or this link for more information. 我的配置不同,您可以查看此讨论此链接以获取更多信息。

1. On the HTML side: 1.在HTML方面:

Respectively Loading jquery and adding a dynamic path to my site: 分别加载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. On the Jquery side: 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. On the Flask side: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM