Home Web Front-end JS Tutorial Ajax+mysq realizes three-level linkage list of provinces and municipalities

Ajax+mysq realizes three-level linkage list of provinces and municipalities

Apr 03, 2018 pm 03:17 PM
Province City District Linkage

This time I will bring you Ajax+mysq to realize the three-level linkage list of provinces and municipalities. What are the precautions for Ajax+mysq to realize the three-level linkage list of provinces and municipalities. The following is a practical case. Get up and take a look.

To implement Ajax to achieve three-level cascading of provinces and municipalities, Java parsing json technology is required
The overall Demo download address is as follows: Click me to download

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(&#39;select&#39;).innerHTML += 
     "<option value=&#39;"+jsonObj.addrList[i].id+"&#39;>"
      +jsonObj.addrList[i].address+
     "</option>"
   }
  }
  //选中省后
  function pChange(){
   //先将市的之前的信息清除
   document.getElementById('selectCity').innerHTML="<option value=&#39;-1&#39;>请选择市</option>";
   //再将区的信息清除
   document.getElementById('selectArea').innerHTML="<option value=&#39;-1&#39;>请选择区</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(&#39;selectCity&#39;).innerHTML += 
     "<option value=&#39;"+jsonObj.cityList[i].id+"&#39;>"
      +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(&#39;selectArea&#39;).innerHTML += 
     "<option value=&#39;"+jsonObj.areaList[i].id+"&#39;>"
      +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=&#39;-1&#39;>请选择市</option>
 </select>
 <select id="selectArea" onchange="aChange()">
  <option value=&#39;-1&#39;>请选择市</option>
 </select>
 <input type="text" id="addr" />
 <button onclick="confirM();">确定</button>
 <p id="show"></p>
</body>
</html>
Copy after login

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);
 }
}
Copy after login

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);
}
Copy after login

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;
 }
}
Copy after login

Entity class 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;
 }
}
Copy after login

I believe you have mastered it after reading the case in this article For more exciting methods, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How does ajax submit a form and implement file upload

Ajax transmits json format data to the background. How to handle errors

The above is the detailed content of Ajax+mysq realizes three-level linkage list of provinces and municipalities. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zhengtu IPx classic animation 'Journey to the West' The journey to the west is fearless and fearless Zhengtu IPx classic animation 'Journey to the West' The journey to the west is fearless and fearless Jun 10, 2024 pm 06:15 PM

Journey through the vastness and set foot on the journey to the west! Today, Zhengtu IP officially announced that it will launch a cross-border cooperation with CCTV animation "Journey to the West" to jointly create a cultural feast that combines tradition and innovation! This cooperation not only marks the in-depth cooperation between the two major domestic classic brands, but also demonstrates the unremitting efforts and persistence of the Zhengtu series on the road of promoting Chinese traditional culture. Since its birth, the Zhengtu series has been loved by players for its profound cultural heritage and diversified gameplay. In terms of cultural inheritance, the Zhengtu series has always maintained respect and love for traditional Chinese culture, and skillfully integrated traditional cultural elements into the game, bringing more fun and inspiration to players. The CCTV animation "Journey to the West" is a classic that has accompanied the growth of generations.

Fried chicken is a great business and there is no room for error! 'Backwater Cold' links up with KFC, causing players to 'dance upon hearing the chicken' Fried chicken is a great business and there is no room for error! 'Backwater Cold' links up with KFC, causing players to 'dance upon hearing the chicken' Apr 17, 2024 pm 06:34 PM

On the date, "Backwater Cold" officially announced that it will launch a linkage with KFC from April 19th to May 12th. However, the specific content of the linkage has left many people stunned. They repeatedly said, "It's embarrassing to heaven" and "It's important to society." died"! The reason lies in the slogan of this theme event. Friends who have seen the KFC linkage of "Genshin Impact" and "Beng Tie" must have the impression that "encountering another world and enjoying delicious food" has become a reality in "Ni Shui Han" Now: shout out to the clerk, "God is investigating the case, who are you?" The clerk needs to reply, "Fried chicken is a big business, and there is no room for error!" Training guide for employees: Never laugh! Not only that, this collaboration also held a dance competition. If you go to the theme store and perform the "Dance when you hear 'Ji'" dance move, you can also get a small rocking music stand. Embarrassing, so embarrassing! But that's what I want

Double chef ecstasy! 'Onmyoji' x 'Hatsune Miku' collaboration starts on March 6 Double chef ecstasy! 'Onmyoji' x 'Hatsune Miku' collaboration starts on March 6 Feb 22, 2024 pm 06:52 PM

NetEase's "Onmyoji" mobile game announced today that the Onmyoji x Hatsune Miku limited collaboration will officially begin on March 6. The collaboration-limited SSR Hatsune Miku (CV: Saki Fujita) and SSR Kagamine Rin (CV: Asami Shimoda) are coming to Heian Kyo! The linkage online special performance event will officially start in the game on March 9~

Classic reunion, reversal of time and space, 'Dragon 2' x 'Westward Journey' movie linkage decision Classic reunion, reversal of time and space, 'Dragon 2' x 'Westward Journey' movie linkage decision Mar 28, 2024 pm 04:40 PM

Classic reunion, reversing time and space. The "Dragon 2" mobile game and the classic movie "Westward Journey" are jointly scheduled to be released on April 11! It coincides with the anniversary celebration of the "Dragon 2" mobile game. We invite everyone to relive the classic memories and once again witness the battle between Zhizunbao and Zixia until death. The legendary story of Chongqing. There must be colorful auspicious clouds, and there must be golden armor and holy clothes. When the phrase "Prajna Paramita" echoes in your ears, will you think of the tear that Zixia left in the heart of the Supreme Treasure? A glance for ten thousand years, but it is impossible to escape the fate of fate. Even if there is no return, my love will never change until death. The Westward Journey collaboration appearance [One Eye for Ten Thousand Years] and [God's Will] will be launched simultaneously with the anniversary version. I hope you can wear the golden armor or meet your own unparalleled hero, and return to your most passionate youth. Five hundred years of protection, true love till death, said by chance when I met Luoyang that day

Linkage and dependency functions of Java development form fields Linkage and dependency functions of Java development form fields Aug 07, 2023 am 08:41 AM

Introduction to the linkage and dependency functions of Java development form fields: In Web development, forms are a frequently used interaction method. Users can fill in information and submit it through the form, but cumbersome and redundant form field selection operations often cause problems for users. bring inconvenience. Therefore, the linkage and dependency functions of form fields are widely used to improve user experience and operational efficiency. This article will introduce how to use Java development to implement linkage and dependency functions of form fields, and provide corresponding code examples. 1. Implementation form of form field linkage function

The collaboration between 'Diablo: Immortal' and 'Legend of Sword and Fairy' has been decided! The collaboration between 'Diablo: Immortal' and 'Legend of Sword and Fairy' has been decided! Apr 17, 2024 pm 02:58 PM

NetEase Games announced today that "Diablo: Immortal" has decided to link up with "Legend of Sword and Fairy". On April 24th, "One Sword is Happy" opens a new era of immortal cultivation! One is a classic of Western fantasy, and the other is the eternal memory of Eastern immortals. The dark universe and the fairy sword are intertwined in time and space, and the two major IPs work together to slay demons. On April 24th, the immortal legend of justice and chivalry will be staged in Sanctuary!

Yuanmeng Star Ultraman genuine linkage: Zero Zeta resonates with the power of Ultra, bursting out with sparks of passion! Yuanmeng Star Ultraman genuine linkage: Zero Zeta resonates with the power of Ultra, bursting out with sparks of passion! Feb 24, 2024 pm 02:25 PM

Yuanmeng Star Ultraman genuine linkage series, Zero Zeta's same fashion details are revealed today. I believe everyone has been looking forward to it for a long time. The co-branded fashion with Zero Zeta has been launched today. Follow the editor to take a look at this I hope it can help you with more details about the Ultraman link-up. Yuanmeng Star Ultraman genuine linkage: Zero Zeta resonates with the power of Ultra, bursting out with sparks of passion! As a new generation of young Ultra Warriors in the Kingdom of Light, Ultraman Zero is the captain of the Ultimate Zero Guard. Ultraman Zero is uninhibited, kind, passionate and unrestrained. "Aren't you still at ease with me by your side? Zero will do his best to protect you." Star treasures, star treasures, put on Ultraman Zero's costumes and fight bravely with Zero! Detailed display, modeling action, appearance action, standby action, Zeta, I am not a one-third dabbler, I am the universe

How to combine ECharts and php interface to realize multi-chart linkage statistical chart display How to combine ECharts and php interface to realize multi-chart linkage statistical chart display Dec 18, 2023 am 10:07 AM

In the field of data visualization, ECharts is a widely used front-end chart library, and its powerful data visualization functions are sought after by various industries. In actual projects, we often encounter situations where multiple charts need to be displayed in a linked manner. This article will introduce how to combine ECharts and PHP interfaces to realize the linked statistical chart display of multiple charts, and give specific code examples. 1. Pre-requisite skills In the practice of this article, you need to master the following skills: basic knowledge of HTML, CSS, and JavaScript;

See all articles