我正在使用python flask
开发和应用程序,我想将Javascript
函数(数组)的返回值发送到python
函数。下面是代码。
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')
我希望将Javascript函数getVals()
中的数组传递给python函数end_stu_live_session
。非常感谢您的帮助。谢谢。
答案 0 :(得分:1)
contentType: 'application/json'
,并在Flask中以request.json
的形式接收数据。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>
输出: