【问题标题】:Rails Rendering a partial within JSONRails在JSON中呈现部分
【发布时间】:2011-10-18 11:31:28
【问题描述】:

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

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

这目前没有返回任何响应,但我的日志显示 shared/mini_posts 已呈现。

请注意,如果我尝试类似:

{
   "html" : "test"
}

这会正确返回。

我的 jQuery 看起来像:

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

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    在我的情况下,我在大约一天半的时间里遇到了同样的问题,在尝试了很多 escape_javascript、to_json、render ... 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);
    })
    

    无需在 Rails 视图中为 \t 和 \n 或 Javascript 中的 JSON.parse 字符串添加 gsub。

    【讨论】:

      【解决方案2】:

      您需要更改控制器。在 respond_to 部分你需要添加 json 渲染。像这样:

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

      然后您可以简单地将 .json 添加到您的 url,您将收到格式为 json 的数据。您可能需要做的是禁用默认情况下自动添加的 JSON 根目录。只需将此行添加到您的环境(development.rb、production.rb、...)配置中:

      config.active_record.include_root_in_json = false
      

      这在解析 json 时很重要。

      【讨论】:

      • 谢谢大卫,我会试一试,让你知道我该怎么做!
      • 当我尝试这个方法时,我得到一个 null 的返回值。我认为这是因为@instancevar(在我的情况下为@index)为空。
      【解决方案3】:

      您不能在部分调用to_json...这是 ActiveRecord 的一种方法。如果你想要json,那么它应该在partial里面。

      【讨论】:

      • 那么有什么方法可以将部分返回为 JSON 吗?还是其他格式?我希望能够使用 AJAX 调用所有内容
      • 你必须在部分内部进行。
      猜你喜欢
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多