Flask+jQuery: AJAX technology dynamically loads web pages

Hello, everyone, my name is wangzirui32, today we will learn how to use jQuery to implement AJAX dynamic loading of web pages.

1. Preparation

There is a lot of preparation work. If you are just coming to learn jQuery, please skip to Part 2-Writing the Loading Code.

1.1 Build a test website

Here I use Python's Flask to build a test website, the code is as follows:

from flask import Flask
from flask import render_template, jsonify
from json import load

# 这个网站主要用来显示图书数据

app = Flask(__name__)
app.config['SECRET_KEY'] = "ashdakjdhasdhw8w"

@app.route("/")
def home():
    return render_template("home.html")

# API数据接口
@app.route("/api/books/data", methods=["GET"])
def books_data():
	# json数据
    with open("books_data.json") as b_d:
        books = load(b_d)
    return jsonify(books)

if __name__ == "__main__":
	# 启动服务器
    app.run(host="127.0.0.1", port=8000, debug=True)

1.2 Data file

Create a json file in the current directory and enter some test data:
books_data.json

[{
    
    "book_name": "Python","book_date": "2020-9-1"},{
    
    "book_name": "C++","book_date": "2020-9-1"}]

These data respectively cover the title and publication date of the book.

1.3 Web page template

Create a folder templates in the current directory, create a home.html file inside, and enter the code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>查看图书信息</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
    <h1>网站图书信息显示</h1>
    <ul id="books"></ul>
    <script src="/static/scripts/main.js"></script>
  </body>
</html>

The script tag in the head is used to load jQuery, and the script tag in the body is used to load the script we will write below.

1.4 Static resources

Create a static folder in the current directory, then create a scripts folder inside, and create a file named main.js in the scripts folder, which is today's protagonist.

2. Write loading code

Enter in main.js (do not understand the comments):

$(function(){
    
    
	// 找到id为books的ul标签
    var $ulBooks = $("#books");

	// 准备请求
    $.ajax({
    
    
        url: '/api/books/data', // 请求地址
        type: 'GET', // 说明请求的类型
        // 请求成功则执行success中的函数
        // data参数说明:由于一个请求会产生多个数据,如状态码,请求头等,我们这里只获取请求到的数据,也就是data
        success: function(data){
    
    
        	// each函数遍历数据
        	// i是索引 item是正在遍历的数据
            $.each(data, function(i, item){
    
    
            	// 在ul标签中加载数据
            	// item.xxx 即可获取该字典某个键对应的值
                $ulBooks.append("<li>图书名称:" + item.book_name + " --- 图书出版日期:" + item.book_date + "</li>");
            });
        },
        // 报错处理
        error: function(){
    
    
        	// 写入日志
            console.log("图书数据加载失败!");
        }
    });
});

The above code loads the json data of the API interface and outputs it to the web page.

3. Effect display

Visit 127.0.0.1:8000, you can see: In
Insert picture description herethis way, our project is completed.

Write at the end

In fact, the project can be expanded, such as adding some personalized webpage code, obtaining other data from the website, and so on. Although the preparations are billions of points long, I hope you can learn the essence of it.


Alright, today’s class is over. If you like, you can order a collection. See you next time!

Guess you like

Origin blog.csdn.net/wangzirui32/article/details/114785492