JQuery UI Autocomplete with JSON data source created from Rails - not working

I am trying to customize an input tag using the jquery autocomplete function, but it does not work when Im refers to external JSON data. However, it works fine with a local JSON-like array ... Let me explain this in my code:

HTML file:

<html>
<head>
 <meta charset="utf-8">

 <script src="jquery-1.4.2.min.js" type="text/javascript"></script> 
 <script src="jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script> 
 <script>
  $(function() {
   $("#birds").autocomplete({
    source: "http://localhost:3000/autocomplete_searches/index.json",
    minLength: 3
   });
  });
 </script>
</head>


<body>
 <div class="ui-widget">
  <label for="birds">Birds: </label>
  <input id="birds" />
 </div>
</body>
</html>

autocomplete_searches_controller.rb in a Rails application

class AutocompleteSearchesController < ApplicationController

 def index
  @tags = Tag.limit(30).name_like(params[:term])
  @tags_hash = []
  @tags.each do |tag|
   @tags_hash << {"label" => tag.label}
  end
  render :json => @tags_hash
 end

end

This JSON action works very well, for example: http: // localhost: 3000 / autocomplete_searches / index? Term = psychiatric gives me:

[{"label":"Psychiatric Hospital"},{"label":"Psychiatric Nurse"},{"label":"Psychiatric Examination"}]

And I see that my jQuery function also works anyway, because when Im typing, for example, "italy" in the #birds input field, WEBrick gives me:

Started GET "/autocomplete_searches/index.json?term=italy" for 127.0.0.1 at 2010-09-27 18:07:07 +0200
  Processing by AutocompleteSearchesController#index as JSON
  Parameteres: {"term"=>"italy"}
  bla bla bla SELECT "tags".* FROM "tags" WHERE (tags.name LIKE '%italy%') LIMIT 30

-. , , script , html . :

<html>
<head>
 <meta charset="utf-8">

 <script src="jquery-1.4.2.min.js" type="text/javascript"></script> 
 <script src="jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script> 
 <script>
  $(function() {
   $("#birds").autocomplete({
    source: [{"label":"Psychiatric Hospital"},{"label":"Psychiatric Nurse"},{"label":"Psychiatric Examination"}],
    minLength: 3
   });
  });
 </script>
</head>


<body>
 <div class="ui-widget">
  <label for="birds">Birds: </label>
  <input id="birds" />
 </div>
</body>
</html>

, ? JSON, , , .

+3
2

Ee... Rails html- . . , html ?

0

, jQuery Validator? , AJAX .

0

Source: https://habr.com/ru/post/1766798/


All Articles