使用数组或列表在JSP中自动完成文本框
我试图以不同的方式进行自动完成,但根本没有任何作用。 从这里到这里
希望你能帮助我们。 我有一个使用Spring MVC + jsp + hibernate的项目。 我想创建一个搜索文本框,它也可以作为客户姓氏的自动完成function。
当我在控制器的帮助下打开客户端页面时,我通过模型发送一个包含客户端的列表和包含姓氏的列表,最后一个用于自动完成。
这是我的控制器:
@Controller @RequestMapping("/clients") public class ClientsController { @Autowired public ClientsService clientsService; @Autowired private ServicesService servicesService; @Autowired private OrdersService ordersService; @Autowired private Order_serviceService order_serviceService; @Autowired private ObjectMapper objectMapper; @RequestMapping(method = RequestMethod.GET) public String listClients(Model model) { List allClients = clientsService.listClients( new RequestAllClientsEvent()).getClients(); List lastNamesList = new ArrayList(); for(int i = 0; i < allClients.size(); i++){ lastNamesList.add(allClients.get(i).getLast_name()); } Collections.sort(lastNamesList); String json = ""; try{ json = objectMapper.writeValueAsString(lastNamesList); } catch(Exception e){} model.addAttribute("clientsList", allClients); model.addAttribute("lastNamesList", json); return "clients"; }
然后在jsp页面中我想添加一些我的lastNamesList到脚本源:
$(function() { $( "#query" ).autocomplete({ source: lastNamesList }); });
我的输入文本框是:
如果我只是写source: lastNamesList
,我想我可以得到类似的内容source: lastNamesList
:
$(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $( "#tags" ).autocomplete({ source: availableTags }); });
能否请你以正确的方式帮助我做到这一点。 如果我能够从我的控制器使用列表或数组,那将是很棒的。 谢谢。
upd.changed我的控制器,添加了json转换,但它没有帮助。 看起来脚本在我的页面上不起作用…更加困惑O_o
UPD。 这是我的工作代码:
控制器:
@RequestMapping(value = "/searchlastname", method = RequestMethod.GET, headers = "Accept=*/*") public @ResponseBody List searchLastName(@RequestParam("term") String query) { List clientsList = clientsService.searchClient(new SearchClientEvent(query)).getClients(); List lastnameList = new ArrayList(); System.out.println("Found clients size: " + clientsList.size()); for (Clients clients : clientsList) { lastnameList.add(clients.getLast_name()); } Collections.sort(lastnameList); return lastnameList; }
脚本:
$(document).ready(function () { $("#lastNameAuto").autocomplete({ source: 'clients/searchlastname' }); });
在jsp中:
<form class="form-horizontal" role="form" action="" method="get">
希望它可以帮助别人! ;)
从您的更新,
您应该有一个模型类并进行显式转换以发送json对象。 要么使用gson
库,要么通过发送列表来使用现有方法。
对于初学者,我建议从这里的好例子中学习
希望这可以帮助 !!