2011-10-18 46 views
0

我想呈现JSON文件中的部分内容,以便通过AJAX使用它。目前在我的JSON文件我有:Rails在JSON中呈现部分内容

<% self.formats = ["html"]%> 
{ 
    "html": "<%= raw escape_javascript(render(:partial => 'shared/mini_posts', :locals => {:type => "left"}).to_json)%>" 
} 

目前这不返回任何响应,但我的日志显示共享/ mini_posts被渲染。

需要注意的是,如果我尝试类似:

{ 
    "html" : "test" 
} 

这正确返回。

我的jQuery的样子:

$j.ajax({ 
    url('/thepage.json'), 
    dataType: 'json', 
    success: function(data){ 
     console.log(data); 
    } 
}) 

回答

0

你需要改变你的控制器。在respond_to部分,你需要添加json渲染。就像这样:

respond_to do |format| 
    format.json { render :json => @instancevar } 
    .... 
    ... 
    .. 
end 

然后,你可以简单地以.json添加到您的网址,您将收到格式化为JSON数据。你可能需要做的是取消默认自动添加的JSON根目录。只是这行添加到您的环境(development.rb,production.rb,...)配置:

config.active_record.include_root_in_json = false 

这一点很重要,当你解析JSON。

+0

谢谢大卫,我会给你一个旋风,让你知道我怎么走! – jwhiting

+0

当我尝试这种方法时,我得到返回值null。我认为这是因为@instancevar(@index在我的情况)为空。 – jwhiting

0

你不能在部分呼叫to_json ...它的ActiveRecord的方法。如果你想让json在那里,那么它应该在部分内部。

+0

那么有什么办法可以返回一个部分为JSON?或以任何其他格式?我希望能够通过AJAX呼叫所有内容 – jwhiting

+0

您必须在部分内部执行此操作。 – bricker

0

在我的情况下,我有相同的问题约一天半,并尝试了escape_javascript,to_json,渲染... content_type等的大量组合后,我终于实现了我正在寻找,即呈现json响应中的HTML部分。

所以在您的控制器你有一个像

def index 
    @candidatos = Candidatos::Base.paginate(page: params[:page], per_page: 3).to_a 
    respond_to do |format| 
     format.html # index.html.erb 
     format.json # index.json.erb 
    end 
end 

一个动作,如果请求有一个以.json它将使用index.json.erb模板,并在我的情况该模板是一样的东西

<% self.formats = ["html"] %> 
{ 
    "html":<%= thumbnails_tag(@candidatos).to_json.html_safe %> 
} 

注意self.formats = ["html"]是必要的,因为否则的“视图”将无法找到部分,因为它会寻找一个部分以.json。更重要的是,不要使用escape_javascript,因为它会用\ t和\ n填充html。换言之,的想法是将您的偏好的输出传递给.to_json,然后传递给.html_safe

thumbnails_tag就是我创建,因为我使用的部分在许多应用程序的部分的帮手,但基本上它有类似

def thumbnails_tag objs 
    #Uncomment the line below to test when no much data available 
    # @listas.fill(@listas.first, 0..6) 
    thumb_span = 4 
    case @candidatos.length 
    when 1..3 
    thumb_span = 12/@candidatos.length 
    else 
    thumb_span = 4 
    end 
    thumbs = {span: thumb_span} 
    render partial: 'candidatos/thumbnails', locals: {candidatos: @candidatos, thumbnail_options: thumbs } 
end 

最后,只是作为一个例子,这种方法在你的.js的资产,你可以这样做:

$.get('http://localhost:3000/candidatos.json?page=2', function(d){}, 'json') 
    .success(function(d){ 
     $('#presidentes div.row-fluid .thumbnails').parent().append(d.html); 
    }) 
    .error(function(event,error){ 
    console.log(error); 
}) 

无需GSUB为\ t和\ n在轨查看或在你的JavaScript JSON.parse字符串。