Table of Contents
三级联动
Home Backend Development PHP Tutorial Example code to implement ajax three-level linkage drop-down menu

Example code to implement ajax three-level linkage drop-down menu

Mar 23, 2017 pm 02:11 PM
ajax Level three linkage Drop-down menu

This article introduces the example code to implement ajax three-level linkage drop-down menu

To write three-level linkage with ajax, first write one File class, you can call it directly when you use it in the future;

Find a table:

Example code to implement ajax three-level linkage drop-down menu

##Realization:

Three regions in China Level linkage: province, city, district;

Picture:

Example code to implement ajax three-level linkage drop-down menu

## Let’s talk about the idea:

(1) When the user selects a province, an event is triggered, and the current province ID is sent to the service through an ajax request. In the terminal program

(2) For example, taking the China region, China is 0001, then the one with the built-in number 0001 is the China region;

Beijing’s code is 11, so the subcode with 11 is the urban area of ​​​​Beijing.

That is to say, query the subcode according to the main code Code name;

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

Displaying the page is very simple, just need a p, and introduce 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 id="三级联动">三级联动</h1>
<p id="sanji"></p>
</body>
</html>
Copy after login

I need three drop-down boxes to select, And give the id writing method

First write three drop-down boxes with the id, and execute the 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, so There are different options depending on the province

Don’t use the click() click event here; use the change event change() that is executed when the state is changed.

(1) When the province changes:

 //当省份发生变化
    $("#sheng").change(function(){
        FillShi();

        FillQu();
    })
Copy after login

Urban areas, districts and counties change

(2) When urban areas change:

 //当市发生改变
    $("#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, write the value 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, before it was "TEXT"

Note: JSON

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

We are using an array, then we need to traverse the array, get each piece of data, and traverse the array in js using What arrived isfor(var sj in data)

{

}

To traverse the array. Format! ! !

这里来写上面说的那个文件封装类,找到我们以前我们的连接数据库的类:

加上这段:

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


嗯,没错

处理页面:

最后来说处理页面:

<?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

连上数据库,对象调用类,写完sql语句直接返回就欧克!!!

就是这么短!

效果图:

Example code to implement ajax three-level linkage drop-down menu

 

相关文章:

用php实现城市地区三级联动 附带数据库

js 实现省市区三级联动菜单效果

Yii2实现中国省市区三级联动实例

The above is the detailed content of Example code to implement ajax three-level linkage drop-down menu. 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)

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 solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

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

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:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

See all articles