我正在开发一个烧瓶网络应用程序,我正在尝试使用jQuery实现类似注释功能,以便在单击like按钮时不必重新加载页面。以下是我的代码。任何帮助都感激不尽。
路线:
@main.route('/like-comment/<int:id>', methods=["GEt", "POST"])
def like_comment(id):
comment = Comment.query.filter_by(id=id).first()
if comment is None:
flash('This comment is invalid or has been deleted by the user')
return redirect(url_for('.home'))
current_user.like_comment(comment)
return jsonify({'result' : 'success', 'like_comment' : current_user.like_comment(comment)})
JavaScript
:
$(document).ready(function() {
$('.like').on('click', function () {
var comment_id = $(this).attr('comment_id');
req = $.ajax({
url : '/like-comment',
type : 'POST',
data : {
like_comment : current_user.like_comment(comment),
id : comment_id
}
});
req.done(function (data) {
$('#like'+comment.id).text(data.like_comment);
});
});
});
HTML
:
{% if not current_user.is_liking_comment(comment) %}
<button class="like btn btn-pill btn-warning btn-xs" comment_id="{{ comment.id }}">
<span class="icon icon-thumbs-up" id="like{{ comment.id }}"></span> Like
</button>
{% else %}
答案 0 :(得分:0)
我不使用flask,但是我看到你正在使用属性“comment_id”,那是一个Flask的东西吗?否则,您应该使用“数据 - ”......
在你的HTML中......
<button class="like btn btn-pill btn-warning btn-xs" data-comment_id="{{ comment.id }}">
然后在jQuery中......
var comment_id = $(this).data('comment_id');
但我认为问题在于您返回的JSON并且您没有向$ .ajax调用表明...
$(document).ready(function() {
$('.like').on('click', function(event) {
event.preventDefault();
var comment_id = $(this).attr('comment_id');
$.ajax({
url : '/like-comment',
type : 'POST',
data : {
like_comment : current_user.like_comment(comment),
id : comment_id
},
dataType='json'
})
.done(function (data) {
$('#like'+comment.id).text(data.like_comment);
});
});
});
或者如果你不想使用Promises ......
$(document).ready(function() {
$('.like').on('click', function(event) {
event.preventDefault();
var comment_id = $(this).attr('comment_id');
$.ajax({
url : '/like-comment',
type : 'POST',
data : {
like_comment : current_user.like_comment(comment),
id : comment_id
},
dataType='json',
success: function(data) {
$('#like'+comment.id).text(data.like_comment);
}
});
});
});
如果有帮助,请告诉我......
答案 1 :(得分:0)
尝试向数据对象添加操作以调用服务器上的函数。见下文:
data: {
action: like_comment, //or the name of your function on the server
like_comment: current_user.like_comment(comment),
id: comment_id,
},