Rails 在 JSON 中呈现部分 [英] Rails Rendering a partial within JSON

查看:40
本文介绍了Rails 在 JSON 中呈现部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to render a partial inside a JSON file so that I can use it via AJAX. Currently in my JSON file I have:

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

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

This currently returns no response, but my logs show that shared/mini_posts was rendered.

请注意,如果我尝试以下操作:

Note that if I try something like:

{
   "html" : "test"
}

这正确返回.

我的 jQuery 看起来像:

My jQuery looks like:

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

推荐答案

您需要更改控制器.在 response_to 部分,您需要添加 json 渲染.像这样:

You need to change your controller. In the respond_to part you need to add json rendering. Like this:

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

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

Then you can simply add .json to your url and you will receive the data formated as json. What you might need to do is disabeling the JSON root hich is automaticly added by default. Just add this line to your environment (development.rb, production.rb,...) configuration:

config.active_record.include_root_in_json = false

这在解析 json 时很重要.

This is important when you are parsing the json.

这篇关于Rails 在 JSON 中呈现部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆