Ajax實現省市區三級級聯(資料來自mysql資料庫)_AJAX相關

來源:互聯網
上載者:User

實現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; }}

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.