Passing Javascript array in Python Flask

倾然丶 夕夏残阳落幕 提交于 2021-02-08 10:27:29

问题


I'm developing and application with python flask and I want to send the return value of a Javascript function(an array) to a python function. Given below is the code.

Javascript

<script>
  function getVals(){
      a = [ab, cd];
      return a;
  }
</script>

HTML

<a href="/end_stu_live_session">End This</a>

Python

@app.route('/end_stu_live_session')
def end_stu_live_session():
   return render_template('stu_dashboard.html')

I want the array from the Javascript function getVals() to be passed to the python function end_stu_live_session. Any help is highly appreciated. Thanks.


回答1:


  • You can send the return value of a Javascript function(an array) to a Python method via Ajax as JSON.
  • Send contentType: 'application/json' from AJAX and receiving the data as request.json in Flask.

app.py:

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/end_stu_live_session',methods=["GET", "POST"])
def end_stu_live_session():
    if request.method == 'POST':
        data = request.json
        return jsonify(data)
    return render_template("home.html")

app.run(debug=True)

home.html:

<html>
    <head>
        <title>Flask Ajax</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <div id="data"></div>       
        <button id="demo_btn">Dummy button</button>
        <script>
            function getVals(){
                  a = ["ab", "cd"];
                  return a;
            }
            $(document).ready(function () {
                $("#demo_btn").on("click", function() {
                    var js_data = JSON.stringify(getVals());
                    $.ajax({                        
                        url: '/end_stu_live_session',
                        type : 'post',
                        contentType: 'application/json',
                        dataType : 'json',
                        data : js_data
                    }).done(function(result) {
                        console.log(result);
                        $("#data").html(result);
                    }).fail(function(jqXHR, textStatus, errorThrown) {
                        console.log("fail: ",textStatus, errorThrown);
                    });
                });
            });
        </script>       
    </body>
</html>

Output:



来源:https://stackoverflow.com/questions/53694709/passing-javascript-array-in-python-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!