Flask+Ajax 的模板如何添加按钮,点击后刷新局部页面

2017-08-26 10:31:27 +08:00
 schema

基本情况: 最近折腾 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

6490 次点击
所在节点    Python
11 条回复
111111111111
2017-08-26 10:57:49 +08:00
了解一下 ajax
LeeSeoung
2017-08-26 11:02:15 +08:00
加一个 button 添加 onclick 事件,发请求,在回调里刷新页面元素。
schema
2017-08-26 11:07:46 +08:00
@LeeSeoung 能不能写下
loading
2017-08-26 11:18:28 +08:00
《锋利的 jQuery 》,去买一本看吧。
Kilerd
2017-08-26 11:51:47 +08:00
楼上都给出思路了,还想要具体代码?😷
pipapa
2017-08-26 12:34:01 +08:00
前端后端分离,发送 post 请求,异步刷新
dong3580
2017-08-26 13:39:39 +08:00
你都说了是 Ajax,先去了解一下何为 Ajax,
fatears
2017-08-26 20:37:46 +08:00
都引入 jquery 了为什么还用原生 js 来写
schema
2017-08-26 21:42:49 +08:00
收藏倒不少了。。。搞不懂 💤
TJT
2017-08-27 16:12:52 +08:00
套个 iframe,然后 reload 这个 iframe 就好了,简单快捷 (滑稽
kitar
2017-08-30 15:43:11 +08:00
<button onclick="newMonitorModal(0)">新建调度</button>

function newMonitorModal(id_) {
$('#modal-content').html("");
$.get(
"{{ url_for('mt.NewMonitor') }}",
{
id: id_
},
function (response) {
$('#modal-content').html(response);
}
}
);
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/385899

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX