Saya memprogram aplikasi web Flask/MySQL/Python/HTML. Ketika saya melakukan pembaruan ke database, saya ingin halaman web saya disegarkan kembali ke blog itu sendiri untuk menampilkan entri baru. Basis data memang diperbarui, tetapi browser tidak akan menyegarkan ke halaman utama.

Ini adalah kode python untuk aplikasi.

    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 adalah halaman yang berisi form untuk menambahkan entri blog baru. Pengalihan akan ke fungsi indeks yang seharusnya memanggil database lagi, mendapatkan data dan mengirimkannya ke halaman home.html dan merender halaman. Ini tidak terjadi. Fungsi ini dipanggil tetapi render_template tidak menyegarkan halaman. Halaman newblog.html tetap ada.

Sunting: Saya tidak punya kode ajax, hanya Jquery yang menangani onclick dan mengirimkannya ke program python.

Ini adalah newblog.html saya yang berisi formulir dan panggilan jquery untuk memproses formulir.

<!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>
0
DaveK 7 Agustus 2019, 22:05

1 menjawab

Jawaban Terbaik

Coba tambahkan header after_request, seperti di bawah ini,

@app.after_request
def adding_header_content(head):
    head.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    head.headers["Pragma"] = "no-cache"
    head.headers["Expires"] = "0"
    head.headers['Cache-Control'] = 'public, max-age=0'
    return head

UPDATE: Memperbarui jawaban setelahnya, kode panggilan ajax Jquery,

Gunakan window.location() untuk mengarahkan ulang browser setelah server mengirimkan respons positif.

success: function (response) {
           window.location("/index");
         },
1
Anup 8 Agustus 2019, 13:50