Good day! I study jquery (Autocomplete), and faced such problem. if I have a list of values ​​in a given array in the script, then everything works:

<script type="text/javascript"> $(function() { var tags = ["tag1", "tag2", "atag3", "btag4", "aaa5"]; $('#acInput').autocomplete({ source: tags }) }); </script> 

But I need to get data from the java collection, for example, by contacting the controller by reference. I read that the java collection will not work, and as an option to transfer the collection to json format.

I tried to write to use such a controller:

 @RequestMapping(value = "/tags", method = RequestMethod.GET) public String getTags() { List<Tag> tags = (List<Tag>) tagService.getAll(); List<String> tagsName = new ArrayList<String>(); for (Tag tag : tags){ tagsName.add(tag.getName()); } String jsonStr = new Gson().toJson(tagsName); return jsonStr; } 

and in the script I specified the link to the controller:

 $(function() { $('#acInput').autocomplete({ source: '/tags' }) }); 

and nothing works. Please help me figure out how to run it all. And what are the options to transfer data to the script from the java collection so that it all works? For example, I have access to the required collection on this jsp, can I use it in a script to solve this task without calling the controller method separately?

I apologize in advance, maybe it is not entirely clear that the problem was stated.

thank

Addition: rewrote the method getTags @RequestMapping (value = "/ tags", method = RequestMethod.GET) public @ResponseBody String getTags () {List tags = (List) tagService.getAll (); List tagsName = new ArrayList (); for (Tag tag: tags) {tagsName.add (tag.getName ()); } String jsonStr = new Gson (). ToJson (tagsName); System.out.println (jsonStr); return new Gson (). toJson (tagsName); }

automatic substitution now works, but shows all tags. That is, sorting does not work, but simply dumps all the data. How to start sorting?

  • what tags returns can stick to the question - L. Vadim
  • thanks, added - Leonid Dubravsky

2 answers 2

You do not have enough tags for tags

 <script type="text/javascript"> $(function() { $('#acInput').autocomplete({ source: 'tags' }) }); </script> 

rewrote the method

 @RequestMapping(value = "/tags", method = RequestMethod.GET) public @ResponseBody String getTags() { List<Tag>tags = (List<Tag>) tagService.getAll(); List<String>tagsName = new ArrayList<String>(); for (Tag tag : tags){ tagsName.add(tag.getName()); } String jsonStr = new Gson().toJson(tagsName); System.out.println(jsonStr); return new Gson().toJson(tagsName); } 

auto substitution works. Other problems have come out, but this is probably a topic for another question.