你的位置:首页 > Java教程

[Java教程]Jquery+ajax+JAVA(servlet)实现下拉菜单异步取值


首先来看工程结构图:

 

项目所需要的包,如下所示:

JSP代码:

 1 <%@ page language="java" import="java.util.*" pageEncoding="GBK"%> 2 <% 3   String path = request.getContextPath(); 4   String basePath = request.getScheme() + "://" 5       + request.getServerName() + ":" + request.getServerPort() 6       + path + "/"; 7       System.out.println("basePath="+basePath); 8 %> 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">10 <html>11 <head>12 <title>JsonCase</title>13 <script type="text/javascript" src="<%=basePath %>js/jquery-1.7.2.min.js"></script>14 <script type="text/javascript">15   $(function($) {16     $("#record").append("当前测试页面完成加载。<br/>");17   });18   function getFirstFloorValue(element) {19     $("#record").append("<br/>获取到信息:您将要取得第一级选项信息……");20     $("#record").append("<br/>正在使用ajax为您获取数据,您可以继续停留在页面并进行其他操作。");21     $.ajax({22       url : 'ValueGetController',23       type : 'post',24       data : 'action=GetFirstFloorValue',25       datatype : 'json',26       success : function(data) {27         $("#record").append("<br/>操作成功,正在为您准备数据……");28         $(element).empty();29         $("#record").append("<br/>清除原始数据成功!");30         var ops = $.parseJSON(data);31         $("#record").append("<br/>即时数据准备成功!");32         for ( var i = 0; i < ops.length; i++)33           $(element).append(34               "<option value=\"" + ops[i] + "\">" + ops[i]35                   + "</option>");36         $("#record").append("<br/>更新列表成功!<br/>");37       }38     });39     40     41   }42 </script>43 </head>44 45 <body>46   <div>47    48     <select id="select1" onfocus=getFirstFloorValue(this)>49       <option value="1">点击取值</option>50     </select>51   </div>52   <dir>53     <h3>记录信息:</h3>54     <span id="record"></span>55   </dir>56 </body>57 </html>

JAVA servlet代码:
 1 package servlet; 2  3 import java.io.IOException; 4 import java.io.PrintWriter; 5  6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse;10 import net.sf.json.JSONArray;11 12 public class ValueGetController extends HttpServlet {13   14   private static final long serialVersionUID = -1293610555518403602L;15 16 17   /**18    * Constructor of the object.19   */20   public ValueGetController() {21     super();22   }23 24   /**25    * Destruction of the servlet. <br>26   */27   public void destroy() {28     super.destroy(); // Just puts "destroy" string in log29     // Put your code here30   }31 32   /**33    * The doGet method of the servlet. <br>34    *35    * This method is called when a form has its tag value method equals to get.36    * 37    * @param request the request send by the client to the server38    * @param response the response send by the server to the client39    * @throws ServletException if an error occurred40    * @throws IOException if an error occurred41   */42   public void doGet(HttpServletRequest request, HttpServletResponse response)43       throws ServletException, IOException {44 45     doPost(request, response);46     47 48   }49 50   /**51    * The doPost method of the servlet. <br>52    *53    * This method is called when a form has its tag value method equals to post.54    * 55    * @param request the request send by the client to the server56    * @param response the response send by the server to the client57    * @throws ServletException if an error occurred58    * @throws IOException if an error occurred59   */60   public void doPost(HttpServletRequest request, HttpServletResponse response)61       throws ServletException, IOException {62 63     request.setCharacterEncoding("GBK");64      response.setContentType("text/html;charset=gbk");65      PrintWriter out = response.getWriter();66      String action = request.getParameter("action");67      System.out.println("action"+action);68      if (action.equals("GetFirstFloorValue")) {69              String[] str = GetFirstFloorValue();70              JSONArray ja = JSONArray.fromObject(str);71              String json = ja.toString();72               out.print(json);73              System.out.println(json);74              out.flush();75               out.close();76              return;77            }78             out.flush();79             out.close();80   }81 82   private String[] GetFirstFloorValue() {83      String[] str = new String[4];84          str[0] = "test1";85          str[1] = "test2";86          str[2] = "test3";87          str[3] = "test4";88          return str;89 90   }91 92   93 94 }

关于servlet的web.

 1 <??> 2 <web-app version="2.5"  3   ="http://java.sun.com/  4   ="http://www.w3.org/2001/  5   xsi:schemaLocation="http://java.sun.com/ 6   http://java.sun.com/> 7  <servlet> 8   <description>This is the description of my J2EE component</description> 9   <display-name>This is the display name of my J2EE component</display-name>10   <servlet-name>ValueGetController</servlet-name>11   <servlet-class>servlet.ValueGetController</servlet-class>12  </servlet>13 14  <servlet-mapping>15   <servlet-name>ValueGetController</servlet-name>16   <url-pattern>/ValueGetController</url-pattern>17  </servlet-mapping>18  19  20   21  <welcome-file-list>22   <welcome-file>index.jsp</welcome-file>23  </welcome-file-list>24 </web-app>