心得:使用异步请求服务端响应的数据既可以是普通文本字符串亦可以是另外一个转发后的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页面的代码示例

 

posted on 2018-08-22 21:33  zeronexyz  阅读(1182)  评论(0编辑  收藏  举报