联动上拉框demo

联动下拉框demo今天课上老师讲了一个联动下拉框的demo,用的是jquery,没连接数据库,是用的JSON数组研究了一

联动下拉框demo

今天课上老师讲了一个联动下拉框的demo,

用的是jquery,没连接数据库,是用的JSON数组

研究了一晚上,貌似搞懂了,现在传上源码与jquery入门新手分享

servlet类

?

package com.newtest;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import com.newtest.vo.Province;public class ProvinceAction extends HttpServlet {/** * Constructor of the object. */public ProvinceAction() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String oper=request.getParameter("oper");if(oper==null){List<Province> list=new ArrayList<Province>();list.add(new Province(1,"四川"));list.add(new Province(2,"广东"));list.add(new Province(3, "湖南"));request.setAttribute("provinceList", list);request.getRequestDispatcher("city_pro.jsp").forward(request, response);}else{response.setContentType("text/html;charset=gbk");String id=request.getParameter("provinceId");System.out.println(id);if("1".equals(id)){JSONObject json=new JSONObject();json.put("id",1);json.put("name","成都");JSONObject json2=new JSONObject();json2.put("id",2);json2.put("name","遂宁");JSONObject json3=new JSONObject();json3.put("id",3);json3.put("name","乐山");JSONArray ja = new JSONArray();ja.add(json);ja.add(json2);ja.add(json3);response.getWriter().println(ja.toString());}if("2".equals(id)){JSONObject json=new JSONObject();json.put("id",1);json.put("name","广州");JSONObject json2=new JSONObject();json2.put("id",2);json2.put("name","顺德");JSONObject json3=new JSONObject();json3.put("id",3);json3.put("name","佛山");JSONArray ja = new JSONArray();ja.add(json);ja.add(json2);ja.add(json3);response.getWriter().println(ja.toString());}if("3".equals(id)){JSONObject json=new JSONObject();json.put("id",1);json.put("name","长沙");JSONObject json2=new JSONObject();json2.put("id",2);json2.put("name","湘潭");JSONObject json3=new JSONObject();json3.put("id",3);json3.put("name","娄底");JSONArray ja = new JSONArray();ja.add(json);ja.add(json2);ja.add(json3);response.getWriter().println(ja.toString());}}}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}

实体类

?package com.newtest.vo;public class Province {private int id;private String name;public Province(int id, String name) {this.id=id;this.name=name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}

?jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'MyJsp.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><script type="text/javascript" src="script/jquery-1.4.2.min.js"></script><script type="text/javascript">  function getCityById(obj){                 var id = obj.value;          $.ajax({                          url: '<%=path %>/Province',              type:'post',              data:{                provinceId:id,                oper:'get'              },              success:function(data){                 var msg = eval('(' + data + ')');                 var city = $("#city");                 city[0].options.length = 1;                 for(var i in msg){                    var option = new Option(msg[i]['name'],msg[i]['id']);                    city[0].add(option);                 }              }          });      }</script>  </head>    <body>         <center>        <h1>联动下拉框</h1>         <select id="province" onchange="getCityById(this);">         <option value="">--请选择省份--</option>            <c:forEach var="province" items="${requestScope.provinceList}">               <option value="${province.id}">${province.name }</option>           </c:forEach>         </select>          <select id="city">           <option value="">--请选择城市--</option>         </select>       </center>     </body></html>

?

是从servlet类进入,如:http://localhost:8080/test_jquery/Province ? (/Province是servlet配置的url-pattern)