如何将一个对象数组(在我的情况下为Users)从控制器传递给jQuery脚本

时间:2022-06-03 11:58:50

I can't understand how to use variables initialized in the controller, for example, to jQuery script (autocomplete in my case). So I'm using Rails and get my authors list. How can I refernce them in jQuery script where I' d like to use jQuery autocomplete plugin like that:

我无法理解如何使用控制器中初始化的变量,例如,jQuery脚本(在我的情况下自动完成)。所以我正在使用Rails并获取我的作者列表。如何在jQuery脚本中引用它们,我想使用这样的jQuery自动完成插件:

[code] $(document).ready(function() { $("#book_author").autocomplete(url or data, options ); }); [/code] So I should pass my authors array from the controler to the script. How to do that?

[code] $(document).ready(function(){$(“#book_author”)。autocomplete(url or data,options);}); [/ code]所以我应该将我的authors数组从控制器传递给脚本。怎么做?

1 个解决方案

#1


You can do it like this.

你可以这样做。

<script type="text/javascript">
  var authors = <%= Author.find(:all).to_json -%>;
  $(document).ready(function() { 
      $("#book_author").autocomplete(authors, options ); });
</script>

The Json string will be evaluated directly in JavaScript as an object. The end result will in this case be something like

Json字符串将直接在JavaScript中作为对象进行评估。在这种情况下,最终结果将是类似的

var authors = [{"author": {"id": 1, "name": "John"}}, {"author": {"id": 2, "name": "Jack"}}];

which will then be an array of objects easily handled in JavaScript. To get it to work with autocomplete you'll probably have to do some more processing though to get it in the format it wants.

然后它将是一个易于在JavaScript中处理的对象数组。为了让它与自动完成功能一起工作,你可能需要做一些更多的处理才能获得它想要的格式。

Just remember that the json string will include the model unless you've turned it off with

请记住,json字符串将包含模型,除非您已将其关闭

ActiveRecord::Base.include_root_in_json = false

#1


You can do it like this.

你可以这样做。

<script type="text/javascript">
  var authors = <%= Author.find(:all).to_json -%>;
  $(document).ready(function() { 
      $("#book_author").autocomplete(authors, options ); });
</script>

The Json string will be evaluated directly in JavaScript as an object. The end result will in this case be something like

Json字符串将直接在JavaScript中作为对象进行评估。在这种情况下,最终结果将是类似的

var authors = [{"author": {"id": 1, "name": "John"}}, {"author": {"id": 2, "name": "Jack"}}];

which will then be an array of objects easily handled in JavaScript. To get it to work with autocomplete you'll probably have to do some more processing though to get it in the format it wants.

然后它将是一个易于在JavaScript中处理的对象数组。为了让它与自动完成功能一起工作,你可能需要做一些更多的处理才能获得它想要的格式。

Just remember that the json string will include the model unless you've turned it off with

请记住,json字符串将包含模型,除非您已将其关闭

ActiveRecord::Base.include_root_in_json = false