【问题标题】:Storing the output of a partial to a local var, then send as json to ajax request将部分输出存储到本地 var,然后作为 json 发送到 ajax 请求
【发布时间】:2011-05-20 20:41:54
【问题描述】:

我有一个 ajax 调用,我想返回一个 json 响应。

控制器将需要获取部分的输出,并为对象添加一些其他属性,然后序列化为 json。

如何获取部分的输出并将其存储到该对象中?

我想要类似的东西:

def my_action

   my_output.html = render :partial => 'test', ....
   my_output.some_prop1 = 234234

   my_output.to_json
end

然后在我看来,我会将 html 注入 DOM 等。

【问题讨论】:

    标签: jquery ruby-on-rails json


    【解决方案1】:

    只需使用render_to_string 代替render

    def my_action
       output = {}
       output[:html] = render_to_string :partial => 'test', ....
       output[:some_prop1] = 234234
       render :json => output
    end
    

    【讨论】:

    • 是否需要先将 my_output 设为特定类型?还是仅仅 my_output = "" 声明就足够了?
    • 顺便说一句,它说找不到模板。当我在没有 render_to_string 的情况下这样做时它起作用了
    • 我的代码:render_to_string :partial => 'test', :locals => { :obj1 => obj1 }, :layout => false
    • 这可能取决于您的 Rails 版本,但如果您将 to_json 传递给 :json =>,我认为您不需要它
    • 我不确定它为什么找不到它。也许你应该通过:partial => 'controller/partial'
    猜你喜欢
    • 2015-02-08
    • 2017-03-05
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 2015-10-16
    • 2023-03-18
    • 2016-06-26
    • 1970-01-01
    相关资源
    最近更新 更多