省市二级联动

来源:互联网 发布:淘宝网男花保 套装 编辑:程序博客网 时间:2024/05/18 20:06

前端代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%    String path = request.getContextPath(); String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><base href="<%=basePath%>"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><select id="province"><option>请选择</option></select>省<select id="city"><option>请选择</option></select>市<script type="text/javascript">function createXMLHttpRequest(){try{return new XMLHttpRequest();}catch(e){try{return new ActiveXObject("Msxml2.XMLHttp");}catch(e){try{return new ActiveObject("Microsoft.XMLHttp");}catch(e){throw e;}}}}window.onload=function(){var pro=document.getElementById("province");var xmlHttp= createXMLHttpRequest();xmlHttp.open("GET","SServlet",true);xmlHttp.send(null);xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState==4 && xmlHttp.status == 200){var data = xmlHttp.responseText;showOption(data);}}//pro.onchange事件使document.getElementById("city")中的内容发生改变,//根据省的id获取市的name值pro.onchange=function(){xmlHttp.open("POST","SServlet",true);xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//通过POST方式发送id值,在SServlet中获取id值xmlHttp.send("id="+pro.value);xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState==4 && xmlHttp.status == 200){var data = xmlHttp.responseText;showOption2(data);}}}}function showOption(data){data=eval("("+data+")");var html="<option>请选择</option>";for(var i=0;i<data.length;i++){var temp=data[i];html += "<option value="+temp.id+">"+temp.name+"</option>";html +="<br/>";}if(html != null){document.getElementById("province").innerHTML=html;}}function showOption2(data){data=eval("("+data+")");var html="<option>请选择</option>";for(var i=0;i<data.length;i++){var temp=data[i];html += "<option>"+temp+"</option>";html +="<br/>";}if(html != null){document.getElementById("city").innerHTML=html;}}</script></body></html>

SServlet.java代码:

package com.lht.servlet;import java.io.IOException;import java.util.List;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.google.gson.Gson;import com.lht.util.UserDao;@WebServlet("/SServlet")public class SServlet extends HttpServlet {private UserDao userDao = new UserDao();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=utf-8");//list为查询出的结果集List<Map<String,Object>> list=userDao.queryProvince();if(list!= null && list.size()>0){//Gson是将Java对象和Json之间的互转,一般用的比较多的两个类库是Jackson和GsonGson gson = new Gson();String json = gson.toJson(list);System.out.println(json+"\r\n");resp.getWriter().write(json);}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=utf-8");//获取到xmlHttp.send("id="+pro.value)的id值 ,即为省的value的值String id=req.getParameter("id");List list = userDao.queryCity(Integer.valueOf(id));if(list!= null && list.size()>0){Gson gson = new Gson();String json = gson.toJson(list);System.out.println(json+"\r\n");resp.getWriter().write(json);}}}

连接数据库,查询代码:
package com.lht.util;import java.sql.Connection;import java.sql.SQLException;import java.util.List;import java.util.Map;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.ArrayListHandler;import org.apache.commons.dbutils.handlers.MapListHandler;import com.lht.po.User;public class UserDao {public List<Map<String,Object>> queryProvince(){Connection conn = null;try {conn = C3p0DataSource.getConnection();QueryRunner qr = new QueryRunner();String sql = "select id,name from lzh_area where reid=1";//查询到的name为key值,id为valuereturn qr.query(conn, sql, new MapListHandler());} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(conn != null){try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return null;}public List queryCity(int id){//传入的id值为省的id,不是省的reidConnection conn = null;try {conn = C3p0DataSource.getConnection();QueryRunner qr = new QueryRunner();//市的reid等于省的id值String sql = "select name from lzh_area where reid=?";Object[] param={id};return qr.query(conn, sql, new ArrayListHandler(),param);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(conn != null){try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return null;}}



原创粉丝点击