Python中Flask+Ajax的模板如何添加按钮,点击后刷新局部页面
基本情况: 最近折腾 Flask,学着做了一个小项目练手。会用简单的 html+css,不会 js
app.py 文件内容如下:
# app.py
import random
from flask import Flask, render_template
app = Flask(name)
One douban film short comment
random output
@app.route("/", methods=[“GET”])
def index():
return render_template(“index.html”)
@app.route("/douban", methods=[‘GET’])
def Comment():
with open(‘douban.txt’, ‘r’) as f:
lines = f.readlines()
num = random.choice(range(len(lines)))
return lines[num]
if name == “main”:
app.run()
模板文件夹 templates 下 index.html 文件内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Flask</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id=“comment”></div>
<script>
$.get(’/douban’).done(function (data) {
var para=document.createElement(“p”);
var node=document.createTextNode(data);
para.appendChild(node);
var element=document.getElementById(“comment”);
element.appendChild(para);
});
</script>
</body>
</html>
现在可以做到的是,按 F5,首页会重新加载一条豆瓣电影短评,但这样不太方便。
所以我想如果在页面内添加一个刷新按钮,点击后 局部刷新 <div id="comment"> 会好很多,请问该怎么做呢
P.S 附上 douban.txt
Python中Flask+Ajax的模板如何添加按钮,点击后刷新局部页面
了解一下 ajax
在Flask里用Ajax实现局部刷新,加个按钮就行。核心是前端用jQuery发Ajax请求,后端返回新数据,前端用JS更新DOM。
后端Flask代码:
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/refresh_data')
def refresh_data():
# 模拟获取新数据
new_data = {'message': '局部内容已更新!', 'timestamp': '2023-10-01 12:00:00'}
return jsonify(new_data)
if __name__ == '__main__':
app.run(debug=True)
前端HTML模板(templates/index.html):
<!DOCTYPE html>
<html>
<head>
<title>Flask Ajax局部刷新</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="content">
<p>初始内容</p>
</div>
<!-- 刷新按钮 -->
<button id="refreshBtn">点击刷新局部内容</button>
<script>
$(document).ready(function(){
$('#refreshBtn').click(function(){
$.ajax({
url: '/refresh_data',
type: 'GET',
success: function(response){
// 更新局部内容
$('#content').html(
'<p>' + response.message + '</p>' +
'<p>时间:' + response.timestamp + '</p>'
);
},
error: function(){
$('#content').html('<p>刷新失败</p>');
}
});
});
});
</script>
</body>
</html>
要点:
- 按钮用
<button id="refreshBtn">定义 - jQuery监听按钮点击事件
- Ajax请求
/refresh_data端点获取JSON数据 - 用
$('#content').html()更新指定区域
总结: 前后端分离,后端提供数据接口,前端用JS处理DOM更新。
加一个 button 添加 onclick 事件,发请求,在回调里刷新页面元素。
能不能写下
《锋利的 jQuery 》,去买一本看吧。
楼上都给出思路了,还想要具体代码?😷
你都说了是 Ajax,先去了解一下何为 Ajax,
收藏倒不少了。。。搞不懂 💤
套个 iframe,然后 reload 这个 iframe 就好了,简单快捷 (滑稽
<button onclick=“newMonitorModal(0)”>新建调度</button>
function newMonitorModal(id_) {
$(’#modal-content’).html("");
$.get(
“{{ url_for(‘mt.NewMonitor’) }}”,
{
id: id_
},
function (response) {
$(’#modal-content’).html(response);
}
}
);
}


