简体   繁体   中英

erb code is not working in javascript <script> tag

I have Post table with title and content attributes. I want to make auto complete textfield where user are suggested by Post title. I am trying to add jquery auto-complete in my rails application. I am doing like this ..

controller (Adding Posts title in Array)--

  @posttitle = []
  Post.all.each do |g|
    @posttitle << g.title 
  end

View --

  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

  <%= text_field_tag :search, params[:search], :placeholder => "Search Religious Places...", :id=>"tags" %>

 <script>
   $(function() {
   var availableTags = <%= @posttitle %>;
   $( "#tags" ).autocomplete({
   source: availableTags
   });
   });
 </script>

But its not showing any suggestion (auto-complete is not working). I don't know whats going wrong. Please help

Have you tried something like this:

<script>
   var availableTags = <%= raw @posttitle %>;
   $(function() {

        $( "#tags" ).autocomplete({
         source: availableTags
        });
   });
</script>

If you want an array of items in Ruby to appear as a javascript array, you'll need to:

1) get it into a comma separated list of values 2) wrap each value in quotes 3) escape the value so that quotes do not cause javascript errors

If you want just the title:

controller:

@titles = Post.pluck(:title)

and then in your view:

 <script>
   $(function() {
     var availableTags = [<%= @titles.map{|title| escape_javascript(title)}.join(", ") %>];
     $( "#tags" ).autocomplete({
       source: availableTags
     });
   });
 </script>

I think you should not use the ruby array in javascript. It will not evaluated as an array. Instead you can create the javascript array and use it as

<script>
  $(function() {
    var availableTags = new Array();
    <% @posttitle.each do |post| %>
      availableTags.push(<%= post %>);
    <% end %>
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM