我需要用两个对象渲染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
Javascript角/ 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
但我不明白如何将remark_count添加到脚本javascripts / comment.js。 我所有尝试插入comments_count,如:
$('#comments_count').html(comments_count);
我收到错误或答案为“true”
请帮帮我!并提前感谢!
==== update =====
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."
});
}
});
}
答案 0 :(得分:1)
据我所知,你返回的对象如下:
{comment: [], comments_count: 100 };
或者可能是{comment: {}, comments_count: 100 };
无论如何这里只返回对象的两个根属性......
因此您应该将其解析为json并将其放置在回调中的元素中:
submitComment = function(form) {
$.ajax("/comments/?format=json", {
type: "post",
dataType: 'json', // <- HERE
data: form.serializeArray(),
success: function(comment) {
$('#comments_count').text(comment.comments_count); // <- AND HERE
$.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."
});
}
});
}
这里有其他奇怪的事情,比如为什么你将注释数组解释为单个注释并尝试获取它的属性id ...但它与问题无关。