【发布时间】:2010-04-15 17:02:06
【问题描述】:
我正在使用 facebooker 插件在 Rails 中实现一个 facebook 应用程序,因此如果我想在我的页面中更新多个 DOM,使用此架构非常重要。 如果我的代码在常规的 Rails 应用程序中运行,它将在我的 facebook 应用程序中运行。
我正在尝试使用 ajax 让用户知道评论已发送,并更新 cmets bloc。
迁移:
class CreateComments < ActiveRecord::Migration
def self.up
create_table :comments do |t|
t.string :body
t.timestamps
end
end
def self.down
drop_table :comments
end
end
控制器:
class CommentsController < ApplicationController
def index
@comments=Comment.all
end
def create
@comment=Comment.create(params[:comment])
if request.xhr?
@comments=Comment.all
render :json=>{:ids_to_update=>[:all_comments,:form_message],
:all_comments=>render_to_string(:partial=>"comments" ),
:form_message=>"Your comment has been added." }
else
redirect_to comments_url
end
end
结束
查看:
<script>
function update_count(str,message_id) {
len=str.length;
if (len < 200) {
$(message_id).innerHTML="<span style='color: green'>"+
(200-len)+" remaining</span>";
} else {
$(message_id).innerHTML="<span style='color: red'>"+
"Comment too long. Only 200 characters allowed.</span>";
}
}
function update_multiple(json) {
for( var i=0; i<json["ids_to_update"].length; i++ ) {
id=json["ids_to_update"][i];
$(id).innerHTML=json[id];
}
}
</script>
<div id="all_comments" >
<%= render :partial=>"comments/comments" %>
</div>
Talk some trash: <br />
<% remote_form_for Comment.new,
:url=>comments_url,
:success=>"update_multiple(request)" do |f|%>
<%= f.text_area :body,
:onchange=>"update_count(this.getValue(),'remaining');" ,
:onkeyup=>"update_count(this.getValue(),'remaining');"
%> <br />
<%= f.submit 'Post'%>
<% end %>
<p id="remaining" > </p>
<p id="form_message" > </p>
<br><br>
<br>
如果我尝试在 update_multiple 函数的第一行执行 alert(json),我得到了一个 [object Object]。
如果我尝试在 update_multiple 函数的第一行执行 alert(json["ids_to_update"][0]) ,则不会显示对话框。
但是评论已保存但没有更新。
问题:
1.javascript 和 rails 怎么知道我在处理 json 对象?deos ROR 给它发送了对象格式还是文本格式?
2.我怎样才能看到返回的json是什么?我必须解析它吗?如何?
2.我该如何调试这个问题?
3.我怎样才能让它工作?
【问题讨论】:
标签: javascript ruby-on-rails ajax json