如何在不加载网页的情况下使用jquery刷新SQLalchemy对象
我正在使用sqlalchemy和flask设计一个简单的博客项目。 在我的索引页面中,我按照发布日期排序的降序加载我的数据库中的可用post列表。 下面是我的index.html代码:
{% extends "base.html" %} {% from "show_links.html" import show_flash_messages %} {% block title %} Home page {% endblock %} {% block jqueryscripts %} $(document).ready(function() { $("#index").css("color","black"); $("#index").html("Home") }); {% endblock %} {% block content %}
{{ show_flash_messages() }} {% if posts %} {% for post in posts.items %} {% endfor %}
{% if posts.has_prev %} Newer Posts → {% else %} {% endif %} {% if posts.has_next %} Older Posts → {% else %} {% endif %} {% else %}
No post to display. Add a new post !
{% endif %} {% endblock %}
下面是我的索引路由的代码:
@posts_blueprint.route('/') @posts_blueprint.route('/index') @posts_blueprint.route('/index/') def index(page=1): posts = [] added_posts = Post.get_all_posts(page) return render_template('index.html',posts=added_posts,user=User.get_current_user())
以下是我的get_all_posts函数的代码:
class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(50)) body = db.Column(db.TEXT) slug = db.Column(db.String(256),unique=True) date = db.Column(db.DATETIME) author_id = db.Column(db.Integer,db.ForeignKey('user.id')) #Relationship with comments(One to many relationship). One post can have many comments comments = db.relationship('Comment', backref='post', lazy='dynamic') #Relationship with tags(Many to many relationship).One post can have many tags and one tag can be associated with many posts tags = db.relationship('Tag',secondary='posts_tags',backref='posts', lazy='dynamic') def __init__(self,title,body,author_id,slug=None): self.title = title self.body = body self.slug = slug self.date = datetime.utcnow() self.author_id = author_id @classmethod def get_all_posts(cls,page): added_posts = [] POSTS_PER_PAGE = 2 added_posts = cls.query.order_by(cls.date.desc()).paginate(page,POSTS_PER_PAGE,False) return added_posts
所以我在sqlalchemy级别进行分页,然后点击按钮显示它们。
现在,这将刷新索引页面,为其提供额外的页码。
现在我不认为这是理想的方法,因为这会刷新整个页面,这会使它变慢。
所以我想用Ajax或jquery刷新post(sqlalchemy)对象。
这甚至可以做到吗?
请有人请一些光。