JQuery實現AJAX異步實現搜索框智能提示功能(百度搜索框智能提示)(傳輸格式為默認普通字符串格式)


心得:使用異步請求服務端響應的數據既可以是普通文本字符串亦可以是另外一個轉發后的jsp頁面(jsp頁面處理后的數據響應給客戶端),也可以是xml數據和json數據,根據不同的數據可以在客戶端作出響應的接受。

 1 <html>
 2 <head>
 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 4 <title>Hello Miss Dang</title>
 5 </head>
 6 <script src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js"></script>
 7 <script type="text/javascript">
 8     $(function(){
 9         $("#word").keyup(function(){
10             var word = $(this).val();//獲得文本框的值
11             if (word != "") {
12                 $.post("${pageContext.request.contextPath}/SearchServlet",{"word":word},function(data){
13                     $("#result").show().html(data);
14                 });
15             }else {
16                 $("#result").hide();
17             }
18         });
19     });
20 </script>
21 <body>
22     <center>
23         <h1>搜索一下</h1>
24         <input id="word" name="word" type="text" style="width: 400px;height: 30px;" /><input type="button" value="百度一下" />
25         <div id = "result" style="display:none;position:absolute;top:120px;left:400px;border: 1px solid blue; width: 400px;height: 300px;"></div>
26     </center>
27 </body>
28 </html>
客戶端代碼示例
 1 public class SearchServlet extends HttpServlet {
 2     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 3         String word = request.getParameter("word");
 4         WordService ws = new WordService();
 5         try {
 6             List<Word> list = ws.search(word);
 7             request.setAttribute("list", list);
 8             request.getRequestDispatcher("/info.jsp").forward(request, response);
 9         } catch (SQLException e) {
10             e.printStackTrace();
11         }
12     }
13     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
14         doGet(request, response);
15     }
16 }
servlet端示例代碼
 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 4 <script type="text/javascript">
 5     var tr = $("#tdata tr");
 6     tr.mouseover(function() {
 7         $(this).css("background-color", "red");
 8         $(this).children("td").css("background-color", "red");
 9     }).mouseout(function() {
10         $(this).css("background-color", "green");
11         $(this).children("td").css("background-color", "#FFFFFF");
12     });
13 </script>
14 <table id="tdata" border="0" width="100%">
15     <c:forEach var="i" items="${ list }">
16         <tr>
17             <td>${ i.word }</td>
18         </tr>
19     </c:forEach>
20 </table>
servlet端轉發到另外一個jsp頁面的代碼示例

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM