AJAX 搜尋欄 站內查詢資料
阿新 • • 發佈:2018-12-17
用到bootstrap
Json的轉換外掛:將java的物件或集合轉成json形式字串
- Gson:google
- fastjson:阿里巴巴
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" /> <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script> <script src="js/bootstrap.min.js" type="text/javascript"></script> <script type="text/javascript"> //2.觸發searchWord事件,得到傳入的引數值 function searchWord(obj) { var word = $(obj).val(); var content = ""; $.post( //地址URL "${pageContext.request.contextPath}/searchWord", //輸入資料 {"word" : word}, //觸發函式 function(data) { //當後臺response.getWriter().write(data) data有值 if (data.length > 0) { //遍歷data 得到值 這裡得到的: //["vivo X5Pro","vivo X5M","中興 AXON","三星 Galaxy S5 (G9008W) 閃耀白","sonim XP7700 4G手機","三星 Galaxy Note5(N9200)32G版","三星 Galaxy S6 Edge+(G9280)32G版 鉑光金","華碩(ASUS)X450J"] // data[i] 訪問資料 for (var i = 0; i < data.length; i++) { content += "<div style='padding:5px;cursor:pointer' onclick='clickFn(this)' onmouseover='overFn(this)' onmouseout='outFn(this)'>" + data[i] + "</div>"; } //填入內容 $("#showDiv").html(content); //將div display變為block $("#showDiv").css("display","block"); } }, //得到資料格式為json "json" ); } //滑鼠移入 div背景變色 function overFn(obj){ $(obj).css("background","#DBEAF9"); } //滑鼠移開 div背景變白 function outFn(obj){ $(obj).css("background","#fff"); } //點選div內容 將當前div的值傳入di為 search 的input內 並且將div display 變成none消失 function clickFn(obj){ $("#search").val($(obj).html()); $("#showDiv").css("display","none"); } </script> </head> <body> <div class="form-group" style="position: relative"> <!--1.用 onkeyup事件繫結searchWord(),當鍵入內容,觸發searchWord函式 --> <input id="search" type="text" class="form-control" placeholder="Search" onkeyup="searchWord(this)"> <div id="showDiv" style="display: none; position: absolute; z-index: 1000; background: #fff; width: 1300px; border: 1px solid #ccc;"> </div> </div> <!-- /input-group --> </body> </html>
data是後臺傳來的資料
//獲得關鍵字 String word = request.getParameter("word"); System.out.println("關鍵字:"+word); //查詢該關鍵字的所有商品 ProductService service = new ProductService(); //productList 是查詢到的物件集合 List<Object> productList = null; try { productList = service.findProductByWord(word); } catch (SQLException e) { e.printStackTrace(); } JSONArray fromObject = JSONArray.fromObject(productList); String string = fromObject.toString(); System.out.println(string); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(string);