【发布时间】:2010-01-18 12:49:52
【问题描述】:
我正在建立一个问答网站,人们可以在其中评论问题及其答案。它是一个带有 ajax 的线程评论系统。
这是 javascript 部分:
function bindPostCommentHandler()
{
$('.commentFormWrapper form').submit(function() {
var current = $(this);
$.ajax({
type: "POST",
data: current.serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
beforeSend:function(xhr){
$('.submit', current).html('<img id="preloader" class="va-mid" src="{{MEDIA_URL}}img/indicator.gif" title="processing.." />');
$('#commentError').remove();
},
success: function(html, textStatus) {
current.parent().replaceWith(html);
bindPostCommentHandler();
},
error: function(xhr, textStatus, errorThrown) {
$('#commentError').remove();
$('.submit', current).html('<input type="submit" name="submit" class="submit-post small-button" value="Submit" />');
if(xhr.status == 400){
current.before('<li id="commentError" class="no-bullet errornote margin10">OOPS ! your comment looked liked a spam. Try again with some modifications.</li>');
}else {
current.before('<li id="commentError" class="no-bullet errornote margin10">Your comment was unable to be posted at this time. You may try after sometime.</li>');
}
//bindPostCommentHandler();
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
html部分:
<!-- comment form for question -->
<div class="commentFormWrapper">
{% render_comment_form for question %}
</div>
<!-- comment form for answers -->
{% for answer in question.answers.all %}
<div class="commentFormWrapper">
{% render_comment_form for answer %}
</div>
问题是,当页面中只有一个表单时,它可以正常工作。使用多种形式,它可以工作,但将请求发送到服务器多次(以倍数增长)。
另外,动态插入/删除表单会更好。但是如果我手动添加表单的 html,我会错过评论表单中的 csrf 令牌和时间戳字段。有人有解决这些问题的方法吗?
【问题讨论】:
-
什么时候调用 bindPostCommentHandler 函数?是否可能被多次调用?
-
我在页面加载时调用一次,在评论成功发布时调用一次。您可以在 $.ajax({...success:function(..){ --here-- } 中看到。问题是由于 html 标签类名而发生的。我应该使用 id 来代替然后绑定。跨度>
-
style="tdisplay:none;",应该是 style="display:none;"吗?