我想仿制微博评论的效果,就是发表评论之后,用户可以实时看见自己发的评论。
我尝试了使用重定向return redirect('main.index')
,可是这样的话,并不能聚焦到原来那条微博的评论列表下面。
想请教下:
1.如果想发表评论后用户能实时看见自己发表的评论,那么在Flask的路由中return语句应该怎么写?
2.这种情况是否应该用ajax来解决??如果是的话,使用jQuery怎么与wtforms渲染的表单配合使用呢?
怪我咯2017-04-18 09:43:56
Weibo is called a single page application (SPA), and the front and back ends are separated and the data is transferred through the API.
I just want to imitate the comment effect, that is, use your own answer, submit the backend api with ajax, and call back to modify the page after saving. The wtform is basically just a decoration, it doesn't matter.
迷茫2017-04-18 09:43:56
It’s best to post your code together.
Here are my suggestions
When you leave a comment, you must be submitting the form, but you need to let the website know in the redirection after the submission form that what you just made was a comment
So, in the redirection after you submit, you You can add a page=-1 to it
Please see the example below
@main.route('/post/<int:id>')
def post(id):
post = Post.query.get_or_404(id)
form = CommentForm()
if form.validate_on_submit():
comment = Comment(body = form.body.data, post = post, author = current_user._get_current_object())
db.session.add(comment)
flash('Your comment has been published.')
return redirect(url_for('.post',id = post.id, page = -1))
page = request.args.get('page',1,type=int)
if page == -1:
page = (post.comments.count()-1)//current_app.config['FLASKY_COMMENTS_PER_PAGE']+1
pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
page,per_page = current_app.config['FLASKY_COMMENTS_PER_PAGE'],
error_out = False)
comments = pagination.items
return render_template('post.html',posts=[post],form = form,comments=comments,pagination = pagination)
The page in the code is used for paging display. You can understand it as the parameter in the url that points to the page.
After he submits the form, what he does is redirect return redirect(url_for('.post',id = post.id, page = -1))
And, url_for can bring **kwargs, so that your request will contain a page=-1
When page == -1, the following statement will pass Calculate (the total number of existing comments) divided by (the number of comments displayed on each page) to calculate the number of pages on the last page
And reassign it to page. At this time, on the comment page below (if displayed in pagination), your comment will be displayed directly to the last page.
I don’t know if you understand what I said.
PHP中文网2017-04-18 09:43:56
Use Websocket. The scale of the website is always suitable for websocket. It is not necessary for single-page applications.