AJAX完成三级级下拉联动【省份-城市-区域】

前端之家收集整理的这篇文章主要介绍了AJAX完成三级级下拉联动【省份-城市-区域】前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

AJAX应用案例--基于MysqL,以POST方式,用DOM对象,完成三级级下拉联动【省份-城市-区域】,效果图如下:


数据库如下:

@H_502_10@省份 城市 区域@H_502_10@

Jsp页面代码:@H_502_10@

@H_502_10@

[html]@H_502_10@ view plain copy
  1. <%@pagelanguage="java"pageEncoding="UTF-8"%>
  2. <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
  3. <html bodyselectid="provinceID"option>请选择省份</optionvalue="1">广东optionvalue="2">湖南selectselectid="cityID">请选择城市selectid="areaID">请选择区域scripttype="text/javascript" functioncreateAJAX(){
  4. varajax=null;
  5. try{
  6. ajax=newActiveXObject("microsoft.xmlhttp");
  7. }catch(e){
  8. try{
  9. ajax=newXMLHttpRequest();
  10. }catch(e){
  11. alert("请更换浏览器");
  12. }
  13. }
  14. returnajax;
  15. script //创建AJAX引擎对象
  16. varajax=createAJAX();
  17. //产生事件
  18. document.getElementById("provinceID").onchange=function(){
  19. //再次选择省份时,清空city下拉框
  20. //定位city下拉框
  21. varcitySelectElement=document.getElementById("cityID");
  22. varoptionElementArray=citySelectElement.options;
  23. varsize=optionElementArray.length;
  24. if(size>1){
  25. for(vari=size-1;i>0;i--){
  26. citySelectElement.removeChild(optionElementArray[i]);
  27. //再次选择省份时,清空area下拉框
  28. //定位area下拉框
  29. varareaSelectElement=document.getElementById("areaID");
  30. varareaOptionArray=areaSelectElement.options;
  31. varsize=areaOptionArray.length;
  32. if(size>1){
  33. for(vari=size-1;i>0;i--){
  34. areaSelectElement.removeChild(areaOptionArray[i]);
  35. //获取选中省份的编号
  36. varoptionElement=this[this.selectedIndex];
  37. varprovinceId=optionElement.value;
  38. //准备发送请求
  39. varmethod="POST";
  40. varurl="${pageContext.request.contextPath}/ProvinceCityAreaServlet?id="+newDate().getTime();
  41. ajax.open(method,url);
  42. //设置以POST表单形式发送,自动将请求体的中文进行编码
  43. ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
  44. //真正发送请求体中的数据
  45. varcontent="provinceId="+provinceId+"&method=provinceToCity";
  46. ajax.send(content);
  47. //监听服务端的响应
  48. ajax.onreadystatechange=function(){
  49. if(ajax.readyState==4){
  50. if(ajax.status==200){
  51. varjsonJavaString=ajax.responseText;
  52. //jsonJavaString=[{"name":"长沙"},{"name":"湘潭"},{"name":"株洲"}]
  53. varjson=eval("("+jsonJavaString+")");
  54. //返回值,就是可解析并执行的JavaScript代码
  55. //json=[{"name":"长沙"},{"name":"株洲"}]
  56. varsize=json.length;
  57. //迭代
  58. for(vari=0;isize;i++){
  59. varcity=json[i].name;
  60. varcid=json[i].id;
  61. //创建option节点
  62. varoptionElement=document.createElement("option");
  63. //设置option节点之间的内容
  64. optionElement.innerHTML=city;
  65. optionElement.setAttribute("value",cid);
  66. //添加到city下拉框中
  67. citySelectElement.appendChild(optionElement);
  68. };
  69. };
  70. //===============================cityToArea==================================================
  71. //产生事件
  72. document.getElementById("cityID").onchange=function(){
  73. //再次选择城市时,定位area下拉框,清空area下拉框
  74. //获取选中城市的编号
  75. varcid=optionElement.value;
  76. varcontent="cid="+cid+"&method=cityToArea";
  77. vararea=json[i].name;
  78. //varcid=json[i].name;
  79. optionElement.innerHTML=area;
  80. //optionElement.setAttribute("id",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px"> areaSelectElement.appendChild(optionElement);
  81. >

servlet代码

@H_502_10@

[java]@H_502_10@ copy
    packagekerwin.servlet;
  1. importjava.io.IOException;
  2. importjava.io.PrintWriter;
  3. importjava.util.List;
  4. importjavax.servlet.ServletException;
  5. importjavax.servlet.http.HttpServlet;
  6. importjavax.servlet.http.HttpServletRequest;
  7. importjavax.servlet.http.HttpServletResponse;
  8. importkerwin.bean.Area;
  9. importkerwin.bean.City;
  10. importkerwin.service.ProvinceCityAreaService;
  11. importnet.sf.json.JSONArray;
  12. importnet.sf.json.JsonConfig;
  13. publicclassProvinceCityAreaServletextendsHttpServlet{
  14. ProvinceCityAreaServiceservice=newProvinceCityAreaService();
  15. voiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  16. request.setCharacterEncoding("utf-8");
  17. Stringmethod=request.getParameter("method");
  18. if("provinceToCity".equals(method)){
  19. this.ProvinceToCity(request,response);
  20. }elseif("cityToArea".equals(method)){
  21. this.cityToArea(request,153); background-color:inherit; font-weight:bold">voiddoPost(HttpServletRequestrequest,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px"> doGet(request,response);
  22. voidProvinceToCity(HttpServletRequestrequest,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px"> response.setContentType("text/html;charset=utf-8");
  23. PrintWriterout=response.getWriter();
  24. List<City>citys=null;
  25. //获取参数
  26. Stringpid=request.getParameter("provinceId");
  27. try{
  28. citys=service.findAllCityByProvince(pid);
  29. //使用第三方工具类,将对象转成JSON格式的字符串
  30. JsonConfigconfig=newJsonConfig();
  31. //去掉不需要的参数
  32. //config.setExcludes(newString[]{"id"});
  33. //将citys转换为json格式的字符串
  34. JSONArrayjsonArray=JSONArray.fromObject(citys,config);
  35. StringjsonJavaStr=jsonArray.toString();
  36. //将字符串响应给ajax引擎
  37. out.write(jsonJavaStr);
  38. catch(Exceptione){
  39. e.printStackTrace();
  40. voidcityToArea(HttpServletRequestrequest,IOException{
  41. response.setContentType("text/html;charset=utf-8");
  42. PrintWriterout=response.getWriter();
  43. List<Area>areas=null;
  44. //获取参数
  45. Stringcid=request.getParameter("cid");
  46. try{
  47. areas=service.findAllAreaByProvince(cid);
  48. //使用第三方工具类,将对象转成JSON格式的字符串
  49. JsonConfigconfig=newJsonConfig();
  50. //去掉不需要的参数
  51. config.setExcludes(newString[]{"id"});
  52. //将citys转换为json格式的字符串
  53. JSONArrayjsonArray=JSONArray.fromObject(areas,config);
  54. StringjsonJavaStr=jsonArray.toString();
  55. //将字符串响应给ajax引擎
  56. out.write(jsonJavaStr);
  57. }catch(Exceptione){
  58. e.printStackTrace();
  59. }

service层代码:省略.....


@H_502_10@

DAO层代码:@H_502_10@

copy

    packagekerwin.dao;
  1. importorg.apache.commons.dbutils.QueryRunner;
  2. importorg.apache.commons.dbutils.handlers.BeanListHandler;
  3. importkerwin.utils.JdbcUtil;
  4. classProvinceCityAreaDao{
  5. publicList<City>findAllCityByProvince(Stringpid)throwsException{
  6. QueryRunnerrunner=newQueryRunner(JdbcUtil.dataSource);
  7. Stringsql="select*fromcityswherepid=?";
  8. Objectparams[]={pid};
  9. citys=runner.query(sql,newBeanListHandler<City>(City.class),params);
  10. returncitys;
  11. publicList<Area>findAllAreaByProvince(Stringcid) List<Area>areas= Stringsql="select*fromareawherecid=?";
  12. Objectparams[]={cid};
  13. areas=runner.query(sql,153); background-color:inherit; font-weight:bold">newBeanListHandler<Area>(Area.returnareas;
  14. }

还有三个province、city、area JavaBean类省略......

MysqL连接使用c3p0连接池:@H_502_10@

c3p0-config.xml:
@H_502_10@

copy
    <?xmlversion="1.0"encoding="UTF-8"?>
  1. c3p0-configdefault-configpropertyname="driverClass">com.MysqL.jdbc.Driverpropertypropertyname="jdbcUrl">jdbc:MysqL://127.0.0.1:3306/ajaxpropertyname="user">rootpropertyname="password"propertyname="acquireIncrement">2propertyname="initialPoolSize">5propertyname="minPoolSize">1propertyname="maxPoolSize"JdbcUtil.java:

    copy

    packagekerwin.utils;
  1. importcom.mchange.v2.c3p0.ComboPooledDataSource;
  2. classJdbcUtil{
  3. staticComboPooledDataSourcedataSource=newComboPooledDataSource();
  4. staticComboPooledDataSourcegetDataSource(){
  5. returndataSource;
  6. }
原文链接:https://www.f2er.com/ajax/165548.html

猜你在找的Ajax相关文章