首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Flask重定向未刷新浏览器页面

Flask重定向未刷新浏览器页面
EN

Stack Overflow用户
提问于 2019-08-08 03:05:26
回答 1查看 2.2K关注 0票数 0

我正在编写一个Flask/MySQL/Python/HTML web应用程序。当我对数据库执行更新时,我希望我的网页刷新回博客本身以显示新条目。数据库会更新,但浏览器不会刷新到主页。

这是应用程序的python代码。

代码语言:javascript
复制
    import pymysql.cursors
    from flask import Flask, render_template, request, json, redirect, url_for
    import datetime

    app = Flask(__name__)

    connection = pymysql.connect(host='localhost',
                                user='root',
                                password='m0nkwork',
                                db='mydb',
                                charset='utf8mb4',
                                cursorclass=pymysql.cursors.DictCursor)

    def FixDates(data):
        for item in data:
            date = item['published']
            item['published'] = date.strftime("%A %B %d, %Y")


    @app.route('/')
    @app.route('/index')
    def index():
        cursor = connection.cursor()
        sql = "SELECT * FROM blogentry"
        cursor.execute(sql)
        data = cursor.fetchall()
        cursor.close()
        FixDates(data)
        return render_template('home.html', data=data)


    @app.route('/NewBlog')
    def NewBlog():
        return render_template('newblog.html')


    @app.route('/NewBlog',methods=['POST'])
    def AddBlog():

        # read the posted values from the UI
        Title = request.form['inputTitle']
        Text = request.form['inputText']
        Author = request.form['inputAuthor']

        # validate the received values
        if Title and Text and Author:
            cursor = connection.cursor()
            # Create a new record
            sql = "INSERT INTO blogentry (blogtitle, blogtext, blogauthor, published) VALUES (%s, %s, %s, %s)" 
            cursor.execute(sql, (Title, Text, Author, datetime.datetime.now()))

            # connection is not autocommit by default. So you must commit to save
            # your changes.
            connection.commit()
            return redirect(url_for('index'))
        else:
            connection.close()
            return render_template('newblog.html')

    if __name__ == '__main__':
        app.run(debug=True)

AddBlog是包含用于添加新博客条目的表单的页面。重定向将转到索引函数,该函数将再次调用数据库,获取数据并将其发送到home.html页面并呈现该页面。这是不会发生的。此函数被调用,但render_template不刷新页面。newblog.html页面保持不变。

编辑:我没有任何ajax代码,只有一个处理onclick并将其发送到python程序的Jquery。

下面是我的newblog.html,它包含表单和处理表单的jquery调用。

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Python Flask Bucket List App</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body>

    <div class="container col-8">
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
                aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                <div class="navbar-nav">
                    <a class="nav-item nav-link active" href="/">Home <span class="sr-only">(current)</span></a>
                    <a class="nav-item nav-link" href="NewBlog">Add New Blog</a>
                </div>
            </div>
        </nav>

        <div class="jumbotron">
            <h1>Bucket List App</h1>
            <form class="form-newblog">
                <label for="inputTitle" class="sr-only">Blog Title</label>
                <input type="name" name="inputTitle" id="inputTitle" class="form-control" placeholder="Add Blog Title"
                    required autofocus>
                <p></p>
                <label for="inputText" class="sr-only">Blog Text</label>
                <textarea rows="5" cols="50" name="inputText" id="inputText" class="form-control" required
                    autofocus></textarea>
                <p></p>
                <label for="inputAuthor" class="sr-only">Author</label>
                <input type="text" name="inputAuthor" id="inputAuthor" class="form-control" placeholder="Author"
                    required>
                <p></p>
                <button id="btnAddNewBlog" class="btn btn-lg btn-primary btn-block" type="button">Add New Entry</button>
            </form>
        </div>

        <footer class="footer">
            <p>&copy; Company 2015</p>
        </footer>

    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
    </script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
    </script>
    <script>
        $(function () {
            $('#btnAddNewBlog').click(function () {

                $.ajax({
                    url: '/NewBlog',
                    data: $('form').serialize(),
                    type: 'POST',
                    success: function (response) {
                        console.log(response);
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });
        });
    </script>
</body>

</html>
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57400850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档