Home Web Front-end JS Tutorial Ajax three-level linkage drop-down menu implementation (with code)

Ajax three-level linkage drop-down menu implementation (with code)

Apr 02, 2018 am 11:09 AM
ajax Drop-down menu accomplish

This time I will bring you the three-level linkage of ajax Drop-down menu Implementation (with code), what are the precautions to implement the ajax three-level linkage drop-down menu, the following is the actual combat Let’s take a look at the case.

To write three-level linkage with ajax, write a file class first, and then call it directly when you use it later;

Find a table:

Realization:

Three-level linkage in China: province, city, district;

Picture:

## Let’s talk about the idea:

(1) When the user selects a province, the event is triggered and the current province id is passed through ajax The request is sent to the program on the server

(2) For example, if the Chinese region is taken, China is 0001, then the one with the number 0001 is the Chinese region;

The code name of Beijing is 11, so the sub-code number 11 is the urban area of ​​​​Beijing.

That is to say, the sub-code number is queried based on the main code number;

(3 ) The server queries the database according to the client's request, and returns it to the client in a certain format

The display page is very simple, it only requires a p, and introduces js and jquery files:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>无标题文档</title>
  <script src="jquery-1.11.2.min.js"></script>
  <script src="sanji.js"></script>
</head>
<body>
<h1>三级联动</h1>
<p id="sanji"></p>
</body>
</html>
Copy after login
I need to select three drop-down boxes and give them id writing methods

First write three drop-down boxes with ids and execute three methods:

$(document).ready(function(e){
  //三个下拉列表
  //加载显示数据
  $("#sanji").html("<select id=&#39;sheng&#39;></select><select id=&#39;shi&#39;></select><select id=&#39;qu&#39;></select>");
  //加载省份
  FillSheng();
  //加载市
  FillShi();
  //加载区
  FillQu();
}
Copy after login
Next Write the method;

The three menus are linked, that is, there are different options according to different provinces

Don’t use click() click event here; use it to execute when changing the state The change event change()

(1) When the province changes:

 //当省份发生变化
  $("#sheng").change(function(){
    FillShi();
    FillQu();
  })
Copy after login
Urban area, district and county change

(2) When the urban area changes :

//当市发生改变
  $("#shi").change(function(){
    FillQu();
  })
});
Copy after login
Districts and counties have changed;

There is nothing wrong with this logic;

The next step is to load the province information roughly, and at the end of the ajax traversal, The value is written into the city's drop-down menu:

//加载省份信息
function FillSheng()
{
  //根据父级代号
  //取父级代号
  var pcode = "0001";
  //根据父级代号查数据
  $.ajax({
    async:false,
    url:"cl.php",
    data:{pcode:pcode},
    type:"POST",
    dataType:"JSON",
    success:function(data)
{
  var str = "";
  for(var sj in data)
  {
    str = str+"<option value = &#39;"+data[sj].AreaCode+"&#39;>"+data[sj].AreaName+"</optiom>";
  }
  $("#sheng").html(str);
}
  });
}
//加载市
function FillShi()
{
  //根据父级代号
  //取父级代号
  var pcode = $("#sheng").val();
  //根据父级代号查数据
  $.ajax({
    async:false,
    //取消异步
    url:"cl.php",
    data:{pcode:pcode},
    type:"POST",
    dataType:"JSON",
  success:function(data)
{
  var str = "";
  for(var sj in data)
  {
    str = str+"<option value = &#39;"+data[sj].AreaCode+"&#39;>"+data[sj].AreaName+"</optiom>";
  }
  $("#shi").html(str);
}
});
}
//加载区
function FillQu()
{
  //根据父级代号
  //取父级代号
  var pcode = $("#shi").val();
  //根据父级代号查数据
  $.ajax({
    url:"cl.php",
    data:{pcode:pcode},
  type:"POST",
    dataType:"JSON",
  success:function(data)
{
  var str = "";
  for(var sj in data)
  {
    str = str+"<option value = &#39;"+data[sj].AreaCode+"&#39;>"+data[sj].AreaName+"</optiom>";
  }
  $("#qu").html(str);
}
});
}
Copy after login
The format here is JSON. Previously, "TEXT" was used

Note: JSON

JSON is a syntax for passing objects. The objects can be name/value pairs, arrays and other objects

We are using arrays, then we need to

Traverse the array, to get each piece of data, the method used to traverse the array in js is

for(var sj in data)

{

}

to traverse the array. Format! ! !

Let’s write the file encapsulation class mentioned above, and find our previous

Connect database class:

Add this paragraph:

public function jsonQuery($sql,$type=1)
  {
    $db = new mysqli($this->host,$this->zhang,$this->mi,$this->dbname);
    $r = $db->query($sql);
    if($type == "1")
    {
      $arr = $r->fetch_all(MYSQLI_ASSOC);
      return json_encode($arr);
//去掉最后竖线
    }
    else
    {
      return $r;
    }
  }
}
Copy after login
Well, that's right

Processing page:

Finally, the processing page:

<?php
$pcode = $_POST["pcode"];
include ("db.class.php");
$db = new db();
$sql = "select * from chinastates where ParentAreaCode = &#39;{$pcode}&#39;";
echo $db->jsonQuery($sql);
Copy after login
Connect to the database, call the object class, and return directly to Ouke after writing the sql statement ! ! !

It’s so short!

Rendering:

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

Recommended reading:

How to use fileinput to implement asynchronous ajax upload

Ajax detailed steps to implement database modification and addition functions

The above is the detailed content of Ajax three-level linkage drop-down menu implementation (with code). 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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to make drop-down menu in WPS table How to make drop-down menu in WPS table Mar 21, 2024 pm 01:31 PM

How to make the WPS table drop-down menu: After selecting the cell where you want to set the drop-down menu, click &quot;Data&quot;, &quot;Validity&quot; in sequence, and then make the corresponding settings in the pop-up dialog box to pull down our menu. As a powerful office software, WPS has the ability to edit documents, statistical data tables, etc., which provides a lot of convenience for many people who need to deal with text, data, etc. In order to skillfully use WPS software to provide us with a lot of convenience, we need to be able to master various very basic operations of WPS software. In this article, the editor will share with you how to use WPS software. Perform drop-down menu operations in the WPS table that appears. After opening the WPS form, first select the

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

See all articles