flask+jquery前後臺交互之拼接div

這是我們要實現的效果
在這裏插入圖片描述

不以jinjia2模板語法的方式來取值,這次我們在後臺組好數據後通過jquery來拼接div的方式來加載博客首頁
先看後臺代碼:

#!/usr/bin/python3  
# -*- coding: utf-8 -*-
# @Time    : 2019/8/26 0026 22:35
# @Author  : P.D
# @Site    : 
# @File    : blogview.py
from flask import Blueprint, render_template, flash, request, jsonify
from models import User, Post


"""
template_folder 指定模板文件位置
static_folder 指定靜態資源文件位置
"""
blue = Blueprint("blog", __name__, static_folder="static", template_folder="templates")


@blue.route("/", methods=['GET', 'POST'])
def index():
    return render_template("index.html")


@blue.route("/get_post_list", methods=['GET', 'POST'])
def get_post_list():
	"""獲取文章列表"""
    post_list = []
    posts = Post.query.all()
    for post in posts:
        post_list.append(post.to_json())
    return jsonify(post_list)

前臺代碼,

{% extends 'base.html' %}

{% block title %}
    <title>博客首頁</title>
{% endblock %}

{% block content %}
    {# 文章列表#}
    <div class="post" style="width: 730px;margin: 0 auto">
    </div>
    

    <script>
        $(function () {
            $.post("/get_post_list", function (data) {
                $.each(data, function (index, item) {
                    var html = $('<a href="#" id="post_title">' + item.title + '</a>' +
                        '<p id="body">' + item.body + '</p>' +
                        '<span id="insert_time">發表時間:' + item.timestamp + '</span>' +
                        '<hr style="border: 1px solid gray">');
                    $(".post").append(html)
                })
            })
        })
    </script>
{% endblock %}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章