欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Ajax实现省市区三级级联(数据来自mysql数据库)

程序员文章站 2022-05-14 21:01:57
实现ajax实现省市区三级级联,需要java解析json技术 整体demo下载地址如下: 点我下载 address.html

实现ajax实现省市区三级级联,需要java解析json技术
整体demo下载地址如下: 点我下载

address.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>insert title here</title>
</head>

 <script type="text/javascript">

  /** 
   * 得到xmlhttprequest对象 
   */
  function getajaxhttp() {
   var xmlhttp;
   try {
    // firefox, opera 8.0+, safari 
    xmlhttp = new xmlhttprequest();
   } catch (e) {
    // internet explorer 
    try {
     xmlhttp = new activexobject("msxml2.xmlhttp");
    } catch (e) {
     try {
      xmlhttp = new activexobject("microsoft.xmlhttp");
     } catch (e) {
      alert("您的浏览器不支持ajax!");
      return false;
     }
    }
   }
   return xmlhttp;
  }
  /** 
   * 发送ajax请求 
   * url--请求到服务器的url 
   * methodtype(post/get) 
   * con (true(异步)|false(同步)) 
   * functionname(回调方法名,不需要引号,这里只有成功的时候才调用) 
   * (注意:这方法有二个参数,一个就是xmlhttp,一个就是要处理的对象) 
   */
  function ajaxrequest(url, methodtype, con, functionname) {
   //获取xmlhttprequest对象
   var xmlhttp = getajaxhttp();
   //设置回调函数(响应的时候调用的函数)
   xmlhttp.onreadystatechange = function() {
    //这个函数中的代码在什么时候被xmlhttprequest对象调用?
    //当服务器响应时,xmlhttprequest对象会自动调用该回调方法
    if (xmlhttp.readystate == 4) {
     if (xmlhttp.status == 200) {
      functionname(xmlhttp.responsetext);
     }
    }
   };
   //创建请求
   xmlhttp.open(methodtype, url, con);
   //发送请求
   xmlhttp.send();
  }

  window.onload=function(){
   ajaxrequest("addressserlvet?method=provincial","post",true,addrresponse);
  }
  //动态获取省的信息
  function addrresponse(responsecontents){
   var jsonobj = new function("return" + responsecontents)();
   for(var i = 0; i < jsonobj.addrlist.length;i++){
    document.getelementbyid('select').innerhtml += 
     "<option value='"+jsonobj.addrlist[i].id+"'>"
      +jsonobj.addrlist[i].address+
     "</option>"
   }
  }
  //选中省后
  function pchange(){
   //先将市的之前的信息清除
   document.getelementbyid('selectcity').innerhtml="<option value='-1'>请选择市</option>";
   //再将区的信息清除
   document.getelementbyid('selectarea').innerhtml="<option value='-1'>请选择区</option>";
   //再将用户的输入清楚
   document.getelementbyid("addr").innerhtml="";
   var val = document.getelementbyid('select').value;
   if(val == -1){
    document.getelementbyid('selectcity')[0].selected = true;
    return;
   }
   //开始执行获取市
   ajaxrequest("addressserlvet?method=city&provincial="+val,"post",true,cityresponse);
  }
  //获取市的动态数据
  function cityresponse(responsecontents){
   var jsonobj = new function("return" + responsecontents)();
   for(var i = 0; i < jsonobj.citylist.length;i++){
    document.getelementbyid('selectcity').innerhtml += 
     "<option value='"+jsonobj.citylist[i].id+"'>"
      +jsonobj.citylist[i].address+
     "</option>"
   }
  }
  //选中市以后
  function cchange(){
   var val = document.getelementbyid('selectcity').value;
   //开始执行获取区
   ajaxrequest("addressserlvet?method=area&cityid="+val,"post",true,arearesponse);
  }
  //获取区的动态数据
  function arearesponse(responsecontents){
   var jsonobj = new function("return" + responsecontents)();
   for(var i = 0; i < jsonobj.arealist.length;i++){
    document.getelementbyid('selectarea').innerhtml += 
     "<option value='"+jsonobj.arealist[i].id+"'>"
      +jsonobj.arealist[i].address+
     "</option>"
   }
  }
  //点击提交按钮
  function confirm(){
   //获取省的文本值
   var p = document.getelementbyid("select");
   var ptex = p.options[p.options.selectedindex].text;
   if(p.value=-1){
    alert("请选择省");
    return;
   }
   //获取市的文本值
   var city = document.getelementbyid("selectcity");
   var citytex = city.options[city.options.selectedindex].text;
   if(city.value=-1){
    alert("请选择市");
    return;
   }
   //获取区的文本值
   var area = document.getelementbyid("selectarea");
   var areatex = area.options[area.options.selectedindex].text;
   if(area.value=-1){
    alert("请选择区");
    return;
   }
   //获取具体位置id文本值
   var addr = document.getelementbyid("addr").value;
   //打印
   document.getelementbyid("show").innerhtml = "您选择的地址为 " + ptex + " " + citytex + " " + areatex + " " + addr;
  }

 </script>
<body>
 <select id="select" onchange="pchange()">
  <option value="-1">请选择省</option>
 </select>
 <select id="selectcity" onchange="cchange()">
  <option value='-1'>请选择市</option>
 </select>
 <select id="selectarea" onchange="achange()">
  <option value='-1'>请选择市</option>
 </select>
 <input type="text" id="addr" />
 <button onclick="confirm();">确定</button>
 <div id="show"></div>
</body>
</html>

addressservlet.java

package cn.bestchance.servlet;

import java.io.ioexception;
import java.util.arraylist;

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 cn.bestchance.dao.addressdao;
import cn.bestchance.dao.impl.addressdaoimpl;
import cn.bestchance.entity.address;
import net.sf.json.jsonarray;
import net.sf.json.jsonobject;

@webservlet("/addressserlvet")
public class addressserlvet extends httpservlet {
 private static final long serialversionuid = 1l;
 private addressdao dao = new addressdaoimpl();

 protected void doget(httpservletrequest request,
   httpservletresponse response) throws servletexception, ioexception {
  dopost(request, response);
 }

 /**
  * @see httpservlet#dopost(httpservletrequest request, httpservletresponse
  *  response)
  */
 protected void dopost(httpservletrequest request,
   httpservletresponse response) throws servletexception, ioexception {

  response.setcharacterencoding("utf-8");
  response.setcontenttype("text/html;charset=utf-8");
  string method=request.getparameter("method");
  if("provincial".equals(method)){
   getprovincial(request, response);
  }
  if("city".equals(method)){
   getcity(request, response);
  }
  if("area".equals(method)){
   getarea(request, response);
  }
 }
 /**
  * 根据市id获取该市下的区的全部信息
  * @param request
  * @param response
  * @throws servletexception
  * @throws ioexception
  */
 protected void getarea(httpservletrequest request,
   httpservletresponse response) throws servletexception, ioexception {

  string cityid = request.getparameter("cityid");
  // 从数据库中查询省的信息
  arraylist<address> arealist = dao.getareabycityid(integer.parseint(cityid));
  // 将集合转成json字符串
  jsonobject jsonobj = new jsonobject();
  jsonarray jsonarray = jsonarray.fromobject(arealist);
  jsonobj.put("arealist", jsonarray);
  string jsondatastr = jsonobj.tostring();

  response.getwriter().print(jsondatastr);
 }
 /**
  * 获取省的信息 并相应
  * @param request
  * @param response
  * @throws servletexception
  * @throws ioexception
  */
 protected void getprovincial(httpservletrequest request,
   httpservletresponse response) throws servletexception, ioexception {

  // 从数据库中查询省的信息
  arraylist<address> addrlist = dao.getprovince();
  // 将集合转成json字符串
  jsonobject jsonobj = new jsonobject();
  jsonarray jsonarray = jsonarray.fromobject(addrlist);
  jsonobj.put("addrlist", jsonarray);
  string jsondatastr = jsonobj.tostring();
  response.getwriter().print(jsondatastr);
 }
 /**
  * 获取市的信息并相应
  * @param request
  * @param response
  * @throws servletexception
  * @throws ioexception
  */
 protected void getcity(httpservletrequest request,
   httpservletresponse response) throws servletexception, ioexception {

  string provinceid = request.getparameter("provincial");
  // 从数据库中查询省的信息
  arraylist<address> addrlist = dao.getcitybyprovinceid(integer.parseint(provinceid));

  // 将集合转成json字符串
  jsonobject jsonobj = new jsonobject();
  jsonarray jsonarray = jsonarray.fromobject(addrlist);
  jsonobj.put("citylist", jsonarray);
  string jsondatastr = jsonobj.tostring();

  response.getwriter().print(jsondatastr);
 }

}

addressdao.java

package cn.bestchance.dao;

import java.util.arraylist;

import cn.bestchance.entity.address;

public interface addressdao {
 /**
  * 获取省的id和名称
  * @return
  */
 arraylist<address> getprovince();
 /**
  * 根据省的id获取市的信息
  * @param provinceid
  * @return
  */
 arraylist<address> getcitybyprovinceid(int provinceid);
 /**
  * 根据市的id获取区的信息
  * @param cityid
  * @return
  */
 arraylist<address> getareabycityid(int cityid);
}

addressdaoimpl.java

package cn.bestchance.dao.impl;

import java.sql.resultset;
import java.sql.sqlexception;
import java.util.arraylist;

import cn.bestchance.dao.addressdao;
import cn.bestchance.entity.address;
import cn.bestchance.util.dbutil;

public class addressdaoimpl implements addressdao {
 private dbutil db = new dbutil();
 @override
 public arraylist<address> getprovince() {
  arraylist<address> addrlist = new arraylist<address>();
  db.openconnection();
  string sql = "select * from province";
  resultset rs = db.excutequery(sql);
  try {
   while(rs.next()){
    address addr = new address();
    addr.setid(rs.getint(2));
    addr.setaddress(rs.getstring(3));
    addrlist.add(addr);
   }
  } catch (sqlexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }finally{
   if(rs != null){
    try {
     rs.close();
    } catch (sqlexception e) {
     // todo auto-generated catch block
     e.printstacktrace();
    }
   }
   db.closeresoure();
  }
  return addrlist;
 }
 @override
 public arraylist<address> getcitybyprovinceid(int provinceid) {
  arraylist<address> addrlist = new arraylist<address>();
  db.openconnection();
  string sql = "select * from city where fatherid = " + provinceid; //431200
  resultset rs = db.excutequery(sql);
  try {
   while(rs.next()){
    address addr = new address();
    addr.setid(rs.getint(2));
    addr.setaddress(rs.getstring(3));
    addrlist.add(addr);
   }
  } catch (sqlexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }finally{
   if(rs != null){
    try {
     rs.close();
    } catch (sqlexception e) {
     // todo auto-generated catch block
     e.printstacktrace();
    }
   }
   db.closeresoure();
  }
  return addrlist;
 }
 @override
 public arraylist<address> getareabycityid(int cityid) {
  arraylist<address> addrlist = new arraylist<address>();
  db.openconnection();
  string sql = "select * from area where fatherid = " + cityid; //431200
  resultset rs = db.excutequery(sql);
  try {
   while(rs.next()){
    address addr = new address();
    addr.setid(rs.getint(2));
    addr.setaddress(rs.getstring(3));
    addrlist.add(addr);
   }
  } catch (sqlexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }finally{
   if(rs != null){
    try {
     rs.close();
    } catch (sqlexception e) {
     // todo auto-generated catch block
     e.printstacktrace();
    }
   }
   db.closeresoure();
  }
  return addrlist;
 }

}

实体类address.java

package cn.bestchance.entity;

public class address {
 @override
 public string tostring() {
  return "address [id=" + id + ", address=" + address + "]";
 }
 private int id;
 private string address;
 public int getid() {
  return id;
 }
 public void setid(int id) {
  this.id = id;
 }
 public string getaddress() {
  return address;
 }
 public void setaddress(string address) {
  this.address = address;
 }
 public address() {
  super();
  // todo auto-generated constructor stub
 }
 public address(int id, string address) {
  super();
  this.id = id;
  this.address = address;
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。