how can I use data posted from ajax in flask?

后端 未结 4 1342
后悔当初
后悔当初 2020-11-28 02:30

I\'m having trouble getting data POSTed from jquery ajax.

$(\'#clickme\').click( function() {
    var data = save_input(); // data

    data[\'_sid\'] = $sur         


        
4条回答
  •  长情又很酷
    2020-11-28 02:50

    As per your example you are not sending a key value pair but rather assigning a JSON string to the jQuery data option. As mentioned in the comments you have to stringify your JSON, create an object with a key (which will be used to access the JSON string from flask) and then assign it to the jQuery data key.

        $.ajax({
                type : "POST",
                url : "{{ url_for('mod.load_ajax') }}",
                data: {json_str: JSON.stringify(data)},
                contentType: 'application/json;charset=UTF-8',
                success: function(result) {
                    console.log(result);
                }
            });
    
        @mod.route('/load_ajax', methods=["GET", "POST"])
        def load_ajax():
            if request.method == "POST":
                # load _sid and _uip from posted JSON and save other data
                # but request.form is empty.
                # >>> request.form
                # ImmutableMultiDict([]) 
                return str(request.form['json_str']
         )
    

提交回复
热议问题