我需要用两个对象渲染 json 怎么做呢?
最初的版本是:
/controller/comments_controller.rb
def create
....
respond_to do |format|
format.html { redirect_to @comment.commentable, flash[:notice] => t('comment.actions.added') }
format.json { render :json => @comment }
end
end
javascripts/comment.js:
submitComment = function(form) {
$.ajax("/comments/?format=json", {
type: "post",
data: form.serializeArray(),
success: function(comment) {
$.get("/comments/" + comment.id, function(commentHtml) {
newComment = $(commentHtml).hide();
commentsList = $('#' + comment.commentable_type + comment.commentable_id + 'Comments');
commentsList.append(newComment);
newComment.show('slow');
});
$(form.selector + " textarea").val("");
},
error: function() {
showMessage({
title: "Error",
message: "Error occured. Please try resubmit the data."
});
}
});
}
我想添加动态更新数量的评论,我认为这样做是:
def create
....
respond_to do |format|
format.html { redirect_to @comment.commentable, flash[:notice] => t('comment.actions.added') }
format.json { render :json => {comment: @comment, comments_count: @comment.commentable.comments.count }
end
end
但我不明白如何将 comments_count 添加到脚本 javascripts/comment.js 中。我插入 comments_count 的所有尝试,例如:
$('#comments_count').html(comments_count);
我得到一个错误或答案“真”
请帮我!并提前感谢!
==== 更新 =====
eicto,谢谢,目前的功能是:
submitComment = function(form) {
$.ajax("/comments/?format=json", {
type: "post",
dataType: 'json',
data: form.serializeArray(),
success: function(comment) {
$("h2#comments_count").text(comment.comments_count);
$.get("/comments/" + comment.comment.id, function(commentHtml) {
newComment = $(commentHtml).hide();
commentsList = $('#' + comment.comment.commentable_type + comment.comment.commentable_id + 'Comments');
commentsList.append(newComment);
newComment.show('slow');
});
$(form.selector + " textarea").val("");
},
error: function() {
showMessage({
title: "Error",
message: "Error occured. Please try resubmit the data."
});
}
});
}