我想做的是当我单击按钮时,它将对Python执行ajax post函数,并获取一些包含要替换先前内容的内容的新变量。
这是我的route.py。
from flask import Flask, jsonify
from flask import render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def main():
table_content = ['jack', 'micheal']
return render_template('index.html',table_content=table_content)
@app.route('/update_data', methods=['GET', 'POST'])
def update_data():
table_content = ['john', 'owen', 'bern']
return jsonify(table_content=table_content)
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Ajax -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<table id="mytable">
{% for content in table_content %}
<tr>
<h4>{{ content }}</h4>
</tr>
{% endfor %}
</table>
<button onclick="refresh()">Click</button>
</body>
<script>
function refresh(){
$.ajax({
url: "/update_data",
type: "POST",
data:'hello'
})
.done(function(data){
console.log(data);
$('#mytable').load(document.URL + ' #mytable');
});
}
</script>
</html>
步骤1:我在main()
函数中具有基本内容,并正常显示在模板中。
第2步:在模板中执行一些操作(单击按钮),然后将ajax发布到python update_data()
函数中。
第3步:“ update_data()”发回一些新变量以更新旧变量数据。