jQuery-UI 学习笔记(二) Autocomplete
1) 下载地址
http://jqueryui.com/download
2) HTML/JSP 写法
<%@ page language="java" %> <%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="java.util.*" %> <%@ page isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <html> <head> <base href="basePath" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Tongue</title> <link type="text/css" rel="stylesheet" href="css/cupertino/jquery-ui-1.8.23.custom.css" /> <link type="text/css" rel="stylesheet" href="css/style.css" /> <script type="text/javascript" src="js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.23.custom.min.js"></script> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#search").autocomplete({ source: "ajax/tongue", minLength: 2, select: function(event, ui) { // alert(ui.item.id); ui.item就是被选中的对象 // alert(ui.item.label); // alert(ui.item.value); } }); }); </script> </head> <body> <div id="wrap"> <input type="text" id="search" /> </div> </body> </html>
3) 后端逻辑
后端应该返回如下类似的JSON字符串
[ { "label": "余雷烨", "value": "@余雷烨 ", "id": "2" }, { "label": "应卓", "value": "@应卓 ", "id": "3" }, { "label": "易志强", "value": "@易志强 ", "id": "5" } ]
显然是一个对象数组,其中"label","value"是必须的,其他根据业务需要可自己添加
@Controller @RequestMapping("/ajax") public class UserTongueController { @Resource private UserService userService; @RequestMapping("/tongue") public ModelAndView tongue(@RequestParam("term") String term) { try { Thread.sleep(1000); } catch (InterruptedException e) { } ModelAndView mav = new ModelAndView("tongue"); if (term.startsWith("@")) { mav.addObject("list", userService.findUserByAlias(term.substring(1))); } return mav; } }
这个JSP用来生成JSON
<%@ page language="java" %> <%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="java.util.*" %> <%@ page isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> [ <c:forEach items="${list}" var="map" varStatus="status"> { "label": "<c:out value="${map['name']}"></c:out>", "value": "@<c:out value="${map['name']} "></c:out>", "id": "<c:out value="${map['id'] }"></c:out>" }<c:if test="${! status.last}">,</c:if> </c:forEach> ]
3) 其他修饰性的部分
.ui-autocomplete-loading { background: white url('../images/ui-anim_basic_16x16.gif') right center no-repeat; }
在输入框右侧加入一个小图片,提示正在加载弹出式的提示框。