我在使用facebooker插件的rails中实现了facebook应用程序,因此如果我想更新页面中的多个DOM,使用此体系结构非常重要。 如果我的代码在普通的rails应用程序中工作,它会在我的Facebook应用程序中工作。如何在rails上使用json和ruby中的json
我想使用ajax让用户知道评论已发送,并更新评论区块。
迁移:
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>
如果我尝试在第一线做警报(JSON) update_multiple函数,我得到了一个[对象对象]。
如果我尝试在update_multiple函数的第一行中执行alert(json [“ids_to_update”] [0]),则不会显示对话框。
但是,评论得到保存,但没有更新。
问题:
JavaScript和轨道1.how可以知道我处理的JSON对象DEOS ROR发送它的对象格式或文本格式?
2.如何查看返回的json是什么?我必须解析它吗?
2. how can debug this problem?
3.我怎么能得到它的工作?
不能得到它的工作,你可以给我一个例子吗? 谢谢 – fenec 2010-04-15 17:39:31
当你试图解析它时发生了什么? – 2010-04-15 18:40:36
什么也没有显示出来,它看起来像是一个零对象 – fenec 2010-04-15 20:07:59