AJAX应用案例--基于mysql,以POST方式,用DOM对象,完成三级级下拉联动【省份-城市-区域】,效果图如下:
数据库如下:
省份 城市 区域
Jsp页面代码:
- <%@ page language="java" pageEncoding="UTF-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <body>
- <select id="provinceID">
- <option>请选择省份</option>
- <option value="1">广东</option>
- <option value="2">湖南</option>
- </select>
- <select id="cityID">
- <option>请选择城市</option>
- </select>
- <select id="areaID">
- <option>请选择区域</option>
- </select>
- <script type="text/javascript">
- function createAJAX(){
- var ajax = null;
- try{
- ajax = new ActiveXObject("microsoft.xmlhttp");
- }catch(e){
- try{
- ajax = new XMLHttpRequest();
- }catch(e){
- alert("请更换浏览器");
- }
- }
- return ajax;
- }
- </script>
- <script type="text/javascript">
- //创建AJAX引擎对象
- var ajax = createAJAX();
- //产生事件
- document.getElementById("provinceID").onchange = function(){
- //再次选择省份时,清空city下拉框
- //定位city下拉框
- var citySelectElement = document.getElementById("cityID");
- var optionElementArray = citySelectElement.options;
- var size = optionElementArray.length;
- if(size>1){
- for(var i=size-1;i>0;i--){
- citySelectElement.removeChild(optionElementArray[i]);
- }
- }
- //再次选择省份时,清空area下拉框
- //定位area下拉框
- var areaSelectElement = document.getElementById("areaID");
- var areaOptionArray = areaSelectElement.options;
- var size = areaOptionArray.length;
- if(size>1){
- for(var i=size-1;i>0;i--){
- areaSelectElement.removeChild(areaOptionArray[i]);
- }
- }
- //获取选中省份的编号
- var optionElement = this[this.selectedIndex];
- var provinceId = optionElement.value;
- //准备发送请求
- var method = "POST";
- var url = "${pageContext.request.contextPath}/ProvinceCityAreaServlet?id="+new Date().getTime();
- ajax.open(method,url);
- //设置以POST表单形式发送,自动将请求体的中文进行编码
- ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
- //真正发送请求体中的数据
- var content = "provinceId="+provinceId + "&method=provinceToCity";
- ajax.send(content);
- //监听服务端的响应
- ajax.onreadystatechange = function(){
- if(ajax.readyState==4){
- if(ajax.status==200){
- var jsonJavaString = ajax.responseText;
- //jsonJavaString = [{"name":"长沙"},{"name":"湘潭"},{"name":"株洲"}]
- var json = eval("("+jsonJavaString+")");
- //返回值,就是可解析并执行的JavaScript代码
- //json = [{"name":"长沙"},{"name":"湘潭"},{"name":"株洲"}]
- var size = json.length;
- //迭代
- for(var i=0;i<size;i++){
- var city = json[i].name;
- var cid = json[i].id;
- //创建option节点
- var optionElement = document.createElement("option");
- //设置option节点之间的内容
- optionElement.innerHTML = city;
- optionElement.setAttribute("value",cid);
- //添加到city下拉框中
- citySelectElement.appendChild(optionElement);
- }
- }
- }
- };
- };
- //===============================cityToArea==================================================
- //产生事件
- document.getElementById("cityID").onchange = function(){
- //再次选择城市时,定位area下拉框,清空area下拉框
- var areaSelectElement = document.getElementById("areaID");
- var areaOptionArray = areaSelectElement.options;
- var size = areaOptionArray.length;
- if(size>1){
- for(var i=size-1;i>0;i--){
- areaSelectElement.removeChild(areaOptionArray[i]);
- }
- }
- //获取选中城市的编号
- var optionElement = this[this.selectedIndex];
- var cid = optionElement.value;
- //准备发送请求
- var method = "POST";
- var url = "${pageContext.request.contextPath}/ProvinceCityAreaServlet?id="+new Date().getTime();
- ajax.open(method,url);
- //设置以POST表单形式发送,自动将请求体的中文进行编码
- ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
- //真正发送请求体中的数据
- var content = "cid="+cid + "&method=cityToArea";
- ajax.send(content);
- //监听服务端的响应
- ajax.onreadystatechange = function(){
- if(ajax.readyState==4){
- if(ajax.status==200){
- var jsonJavaString = ajax.responseText;
- //jsonJavaString = [{"name":"长沙"},{"name":"湘潭"},{"name":"株洲"}]
- var json = eval("("+jsonJavaString+")");
- //返回值,就是可解析并执行的JavaScript代码
- //json = [{"name":"长沙"},{"name":"湘潭"},{"name":"株洲"}]
- var size = json.length;
- //迭代
- for(var i=0;i<size;i++){
- var area = json[i].name;
- //var cid = json[i].name;
- //创建option节点
- var optionElement = document.createElement("option");
- //设置option节点之间的内容
- optionElement.innerHTML = area;
- //optionElement.setAttribute("id",cid);
- //添加到city下拉框中
- areaSelectElement.appendChild(optionElement);
- }
- }
- }
- };
- };
- </script>
- </body>
- </html>
servlet代码:
- package kerwin.servlet;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import kerwin.bean.Area;
- import kerwin.bean.City;
- import kerwin.service.ProvinceCityAreaService;
- import net.sf.json.JSONArray;
- import net.sf.json.JsonConfig;
- public class ProvinceCityAreaServlet extends HttpServlet {
- ProvinceCityAreaService service = new ProvinceCityAreaService();
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- String method = request.getParameter("method");
- if("provinceToCity".equals(method)){
- this.ProvinceToCity(request, response);
- }else if("cityToArea".equals(method)){
- this.cityToArea(request, response);
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doGet(request, response);
- }
- public void ProvinceToCity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.setContentType("text/html; charset=utf-8");
- PrintWriter out = response.getWriter();
- List<City> citys = null;
- //获取参数
- String pid = request.getParameter("provinceId");
- try {
- citys = service.findAllCityByProvince(pid);
- //使用第三方工具类,将对象转成JSON格式的字符串
- JsonConfig config = new JsonConfig();
- //去掉不需要的参数
- //config.setExcludes(new String[]{"id"});
- //将citys转换为json格式的字符串
- JSONArray jsonArray = JSONArray.fromObject(citys, config);
- String jsonJavaStr = jsonArray.toString();
- //将字符串响应给ajax引擎
- out.write(jsonJavaStr);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void cityToArea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.setContentType("text/html; charset=utf-8");
- PrintWriter out = response.getWriter();
- List<Area> areas = null;
- //获取参数
- String cid = request.getParameter("cid");
- try {
- areas = service.findAllAreaByProvince(cid);
- //使用第三方工具类,将对象转成JSON格式的字符串
- JsonConfig config = new JsonConfig();
- //去掉不需要的参数
- config.setExcludes(new String[]{"id"});
- //将citys转换为json格式的字符串
- JSONArray jsonArray = JSONArray.fromObject(areas, config);
- String jsonJavaStr = jsonArray.toString();
- //将字符串响应给ajax引擎
- out.write(jsonJavaStr);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
service层代码:省略.....
DAO层代码:
- package kerwin.dao;
- import java.util.List;
- import org.apache.commons.dbutils.QueryRunner;
- import org.apache.commons.dbutils.handlers.BeanListHandler;
- import kerwin.bean.Area;
- import kerwin.bean.City;
- import kerwin.utils.JdbcUtil;
- public class ProvinceCityAreaDao{
- public List<City> findAllCityByProvince(String pid) throws Exception{
- List<City> citys = null;
- QueryRunner runner = new QueryRunner(JdbcUtil.dataSource);
- String sql = "select * from citys where pid = ?";
- Object params[]={pid};
- citys = runner.query(sql, new BeanListHandler<City>(City.class), params);
- return citys;
- }
- public List<Area> findAllAreaByProvince(String cid) throws Exception{
- List<Area> areas = null;
- QueryRunner runner = new QueryRunner(JdbcUtil.dataSource);
- String sql = "select * from area where cid = ?";
- Object params[]={cid};
- areas = runner.query(sql, new BeanListHandler<Area>(Area.class), params);
- return areas;
- }
- }
还有三个province、city、area JavaBean类省略......
mysql连接使用c3p0连接池:
c3p0-config.xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <c3p0-config>
- <default-config>
- <property name="driverClass">com.mysql.jdbc.Driver</property>
- <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/ajax</property>
- <property name="user">root</property>
- <property name="password">root</property>
- <property name="acquireIncrement">2</property>
- <property name="initialPoolSize">5</property>
- <property name="minPoolSize">1</property>
- <property name="maxPoolSize">5</property>
- </default-config>
- </c3p0-config>
JdbcUtil.java:
- package kerwin.utils;
- import com.mchange.v2.c3p0.ComboPooledDataSource;
- public class JdbcUtil {
- public static ComboPooledDataSource dataSource = new ComboPooledDataSource();
- public static ComboPooledDataSource getDataSource() {
- return dataSource;
- }
- }