jQuery 在 Rails 3 中处理 JS/ERB 模板中的 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3757457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:02:39  来源:igfitidea点击:

Handling JSON in JS/ERB template in Rails 3

jqueryruby-on-railsajaxjsonerb

提问by Michael Waxman

I have no trouble making typical AJAX calls to and from Rails(3) with JSON objects and jQuery-rails (jQuery library plus a special rails.js file).

我可以使用 JSON 对象和 jQuery-rails(jQuery 库和一个特殊的 rails.js 文件)与 Rails(3) 进行典型的 AJAX 调用。

In one controller, though, I want to RETURN some JSON in an erb template (create.js.erb) after an AJAX call.

但是,在一个控制器中,我想在 AJAX 调用后在 erb 模板 (create.js.erb) 中返回一些 JSON。

I've tried every combination of things in the controller (@object.to_json, '[{"content":"hello world"}]', etc.) and in the template itself (JSON.parse(), single quotes, double quotes, etc.), but the object keeps on rendering like this:

我已经尝试了控制器(@object.to_json、'[{"content":"hello world"}]' 等)和模板本身(JSON.parse()、单引号、双引号等),但对象继续呈现如下:

'[{"groups":{},"created_at":"2010-09-21T03:49:34Z" ...

and as a result, my jQuery code cannot parse it and I get errors.

结果,我的 jQuery 代码无法解析它并且出现错误。

How do I need to prep my object in the controller, and what erb syntax do I need in the view for it to render as a valid JSON object?

我需要如何在控制器中准备我的对象,我需要在视图中使用什么 erb 语法才能将它呈现为有效的 JSON 对象?

Thanks so much!

非常感谢!

回答by alex.zherdev

I'm not sure this is the cause, but you can also try playing around with html_safemethod. ERB might be escaping your JSON because it thinks it's not html safe. Try calling that method when using the string:

我不确定这是原因,但您也可以尝试使用html_safe方法。ERB 可能会转义您的 JSON,因为它认为它不是 html 安全的。尝试在使用字符串时调用该方法:

@object.to_json.html_safe

回答by John

Using html_escapeor rawalone will leave you vulnerable to XSS.

使用html_escaperaw单独会使您容易受到 XSS 的攻击

Instead, define a sensible version of the json_escape(a.k.a. j) helper:

相反,定义json_escape(又名j)助手的合理版本:

module ActionView::Base
  def json_escape(s)
    result = s.to_s.gsub('/', '\/')
    s.html_safe? ? result.html_safe : result
  end

  alias j json_escape
end

Use it like this:

像这样使用它:

<script>
  var Accounts = new Backbone.Collection;
  Accounts.reset(<%=j @accounts.to_json.html_safe %>);
  var Projects = new Backbone.Collection;
  Projects.reset(<%=j @projects.to_json(:collaborators => true).html_safe %>);
</script>

See this postfor further details.

有关更多详细信息,请参阅此帖子

Be aware that there's a naming conflictbetween jaliased to json_escapein ERB::Util and jaliased to escape_javascriptin ActionView::Helpers::JavaScriptHelper. It's my hope that the JavaScriptHelper alias will be renamed to js.

要知道,有一个命名冲突之间j化名为json_escape在ERB ::的Util并j化名为escape_javascript在::的ActionView ::助手JavaScriptHelper。我希望 JavaScriptHelper 别名将重命名为js.

回答by nathanvda

To return jsonyou have to write your render in the controller as follows:

要返回,json您必须在控制器中编写渲染如下:

render :json => @object

and the .to_jsonwill automatically be called.

并且.to_json会自动被调用。

If you would want to include some relations, you could do the following:

如果您想包含一些关系,您可以执行以下操作:

render :json => @post.to_json(:include => [:comments, :authors])

I am not sure if it would work to use an erb to render your json.

我不确定使用 erb 来呈现您的 json 是否可行。

回答by wkhatch

You can call render in your controller, but that will be a problem if you need to possibly render more than a few partials for subsequent dom insertion by the handler. I needed to set multiple html fragments into a hash, and I've been able to return erb which basically uses hash.to_json.html_safe as neutrino suggests above and allows me to render multiple partials in the process.

您可以在控制器中调用渲染,但是如果您需要为处理程序随后的 dom 插入渲染多个部分,这将是一个问题。我需要将多个 html 片段设置为一个散列,并且我已经能够返回 erb ,它基本上使用 hash.to_json.html_safe ,正如上面neutrino 建议的那样,并允许我在此过程中呈现多个部分。

回答by brauliobo

Only to_json.html_safeis needed:

to_json.html_safe需要:

> `'<script>'.to_json`
=> "\"\u003cscript\u003e\""

Patch to make to_jsonrespond to html_safe?and return trueautomatically:

使to_json响应html_safe?true自动返回的补丁:

# just use .to_json instead of .to_json.html_safe
ActiveSupport::JSON.class_eval do
  class << self
    def encode_with_html_safe *args
      self.encode_without_html_safe(*args).html_safe
    end
    alias_method_chain :encode, :html_safe
  end
end