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:
[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?
-
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
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.
Just remember that the json string will include the model unless you've turned it off with
ActiveRecord::Base.include_root_in_json = false
0 comments:
Post a Comment