Passing data from javascript into Flask

后端 未结 3 786
南方客
南方客 2020-12-08 17:21

I know how to pass data with a jinja template from python into javascript, but I want to pass a javascript variable into python. I\'d like to do it without reloading the pag

3条回答
  •  青春惊慌失措
    2020-12-08 17:41

    I did a similar kind of work in my project and would like to share my code here. I need to find out which post is selected and I was setting the selected post as a global variable at server side, so that I may use it for later comparison. This is how I pass my selected post into Javascript.

     Compare
    

    Now from Javascript to Flask.

    function myFunction(x) {
            $.getJSON($SCRIPT_ROOT + '/check_selected', {
            post: x
            }, function(data) {
                var response = data.result;
                console.log(response);
                }
            });
    }
    

    This is how I return the result from flask by using JSON.

    import json
    @main.route('/check_selected', methods=['GET','POST'])
    def check_selected():
        global selected
        post = request.args.get('post', 0, type=int)
        return json.dumps({'selected post': str(post)});
    

    As mentioned here, we need to include Google AJAX API in order to load jquery:

    
    
    

提交回复
热议问题