Rails:在HTML中调用to_json方法

时间:2015-02-17 10:51:01

标签: javascript html ruby-on-rails ruby-on-rails-4

我如何在下面的数据过滤器上调用.to_json?

data-filters="<%= t.AB_filterRules %>"

我问的原因是因为我的HTML ERB文件中有data-filters属性,它显示数据库属性。示例如下:

data-filters="[[{" noun":"app","comparison":"was","value":”opened in the last two days"},{"noun":"deliverable","comparison":"is","value":"push notification"}]]"

但是,当我在控制台中查看data-filters属性的值时,它只显示:

"[[{"

我真的很喜欢这一切,所以在这里调用.to_json非常有帮助!

由于

1 个答案:

答案 0 :(得分:1)

要考虑到这一点的关键是:如果这是注定要被javascript函数读取,并转换回javascript对象,那么它可以以任何方式呈现在页面上无论如何,只要可以在javascript函数中再次翻译

我们将&#34;对象用于字符串&#34; ruby中的翻译,&#34;字符串到对象&#34;在javascript中进行翻译,因此我们需要选择一些在两种语言中以标准方式工作的翻译系统。我在ruby中使用URI.escape,在javascript中使用decodeURIComponentURI.escape是一个标准系统(意味着规则应该在不同语言中相同)并且是网络安全的,这意味着结果不应该包含任何会破坏url或html标记的字符。

在erb模板中

<% @rules = [[{" noun" => "app","comparison" => "was","value" => "opened in the last two days"},{"noun" => "deliverable","comparison" => "is","value" =>"push notification"}]] %>

<div id="data-filters-test" data-filters="<%= URI.escape(@rules.to_json) %>"></div>

显然你可以用自己的方法替换@rules,从数据库中读取数据或其他:上面只是我的版本所以我可以测试它。

结果html:

<div id="data-filters-test" data-filters="[[%7B%22value%22:%22opened%20in%20the%20last%20two%20days%22,%22%20noun%22:%22app%22,%22comparison%22:%22was%22%7D,%7B%22noun%22:%22deliverable%22,%22value%22:%22push%20notification%22,%22comparison%22:%22is%22%7D]]"></div>

您的最后一步是将此URI.escape&#39;字符串转换回javascript中的对象。我会这样做:(以下列出了每个步骤的结果,以供解释)

//get the string
var escapedString = $("#data-filters-test").data("filters");
// => "[[%7B%22value%22:%22opened%20in%20the%20last%20two%20days%22,%22%20noun%22:%22app%22,%22comparison%22:%22was%22%7D,%7B%22noun%22:%22deliverable%22,%22value%22:%22push%20notification%22,%22comparison%22:%22is%22%7D]]"

//reverse the URI.escape, to get it back to json
var json = decodeURIComponent(escapedString);
// => "[[{"value":"opened in the last two days"," noun":"app","comparison":"was"},{"noun":"deliverable","value":"push notification","comparison":"is"}]]"

//convert the json string to a javascript object
var filter = JSON.parse(json);
// => <Object>

显然,如果你想要,或者更好的是一个功能,你可以将这一切包装在一个步骤中,例如

function uriEscapedToObject(escapedString){
  return JSON.parse(decodeURIComponent(escapedString));
}

现在在你的js中处理这个元素你可以写

var filters = uriEscapedToObject($("#data-filters-test").data("filters"));