search
HomeWeb Front-endJS TutorialAjax realizes three-level cascading of provinces and municipalities (data comes from mysql database)

This article mainly introduces Ajax to realize the three-level cascade of provinces and municipalities in detail. The data comes from mysql database. It has certain reference and value for learning Ajax. Friends who are interested in ajax You can refer to

Implementing Ajax to realize three-level cascading of provinces and municipalities requires Java parsing json technology
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(&#39;selectCity&#39;).innerHTML="<option value=&#39;-1&#39;>请选择市</option>";
   //再将区的信息清除
   document.getElementById(&#39;selectArea&#39;).innerHTML="<option value=&#39;-1&#39;>请选择区</option>";
   //再将用户的输入清楚
   document.getElementById("addr").innerHTML="";
   var val = document.getElementById(&#39;select&#39;).value;
   if(val == -1){
    document.getElementById(&#39;selectCity&#39;)[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(&#39;selectCity&#39;).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>


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

}


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

}


The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

Related recommendations:

jq, ajax, php, mysql to implement keyword fuzzy query

Simple implementation of Ajax without refresh Pagination effect

The perfect solution for Ajax cross-domain requests that COOKIE cannot bring

The above is the detailed content of Ajax realizes three-level cascading of provinces and municipalities (data comes from mysql database). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),