How to use ajax in php to achieve provincial linkage

PHPz
Release: 2023-03-29 10:53:50
Original
466 people have browsed it

In web development, provincial linkage is one of the very common functions. For example, in an address filling form, users need to first select their province, and then make a selection based on the city data of the selected province. The realization of this function mainly relies on the collaboration between front-end technology and back-end technology. In this article, we will introduce how to use PHP and AJAX technology to implement provincial linkage functions.

  1. Preparation work

Before using PHP and AJAX to achieve provincial linkage, we need to prepare some necessary work. First, we need a city database. This database contains data for all provinces, cities and counties. This database can be MySQL, Oracle, MSSQL Server, etc. In this article, we use the MySQL database.

In addition, we also need some front-end technologies, such as HTML, CSS, and Javascript. These technologies can help us build highly interactive user interfaces. In this user interface, users can select their province and city through drop-down menus.

  1. Building a city database

Before creating a city database, we need to design the data structure of this database. It mainly contains the following data tables:

  • Province table (province): Contains province id and province name fields;
  • City table (city): Contains city id, city name and province id field;
  • County table (area): includes county id, county name and city id fields.

Use the following SQL statement to create a table:

--Province table
CREATE TABLE province (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

-- City table
CREATE TABLE city (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
province_id int(11) NOT NULL,
PRIMARY KEY (id),
KEY province_id (province_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- County table
CREATE TABLE area (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
city_id int(11) NOT NULL,
PRIMARY KEY (id),
KEY city_id (city_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Import city data into these three tables, and we can start building PHP code.

  1. Build provincial linkage code

The following is the process of PHP code implementation:

  • When the user selects a province (through the drop-down menu method), the AJAX code sends the selected province id to the back-end server;
  • After the back-end server receives the province id, it queries the database to return the list of cities to which the province belongs;
  • AJAX code Update the city list to the front-end page so users can continue to select cities.

Following the above process, we can write the following PHP code:

  • province.php
<?php
// 获取所有省份信息
$conn = mysqli_connect("localhost", "root", "password", "test");
$sql = "SELECT id, name FROM province ORDER BY id ASC";
$result = mysqli_query($conn, $sql);
$provinceArray = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($provinceArray, $row);
}
mysqli_close($conn);

// 输出省份信息
echo json_encode($provinceArray, JSON_UNESCAPED_UNICODE);
?>
Copy after login
  • city.php
<?php
// 获取所选省份对应的城市信息
$provinceId = $_GET[&#39;provinceId&#39;];
$conn = mysqli_connect("localhost", "root", "password", "test");
$sql = "SELECT id, name FROM city WHERE province_id=$provinceId ORDER BY id ASC";
$result = mysqli_query($conn, $sql);
$cityArray = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($cityArray, $row);
}
mysqli_close($conn);

// 输出城市信息
echo json_encode($cityArray, JSON_UNESCAPED_UNICODE);
?>
Copy after login
  • area.php
<?php
// 获取所选城市对应的县区信息
$cityId = $_GET[&#39;cityId&#39;];
$conn = mysqli_connect("localhost", "root", "password", "test");
$sql = "SELECT id, name FROM area WHERE city_id=$cityId ORDER BY id ASC";
$result = mysqli_query($conn, $sql);
$areaArray = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($areaArray, $row);
}
mysqli_close($conn);

// 输出县区信息
echo json_encode($areaArray, JSON_UNESCAPED_UNICODE);
?>
Copy after login

Here we use mysqli to connect to the database. Before use, you need to change "localhost", "root" and " password" with the corresponding hostname, username, and password. At the same time, we also need to test the database name into the corresponding database.

  1. Building the front-end interface

In building the front-end interface, we mainly need to use HTML, CSS and Javascript technologies. The following are the main steps to implement provincial linkage on the front end:

  • Define two drop-down menus: one for selecting a province and the other for selecting a city;
  • When the user selects After a province, send a request to the back-end server to obtain the list of cities corresponding to the province;
  • Update the city drop-down list so that the user can continue to select a city.

The following is the HTML and Javascript code implemented:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>省级联动</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <select id="provinceSelect">
        <option value="">请选择省份</option>
    </select>
    <select id="citySelect">
        <option value="">请选择城市</option>
    </select>
    <select id="areaSelect">
        <option value="">请选择县区</option>
    </select>
    <script>
        $(document).ready(function () {
            // 页面加载时获取所有省份信息
            $.ajax({
                url: 'province.php',
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    // 循环添加省份列表
                    $.each(data, function (i, item) {
                        $('#provinceSelect').append('<option value="&#39; + item.id + &#39;">' + item.name + '</option>');
                    });
                }
            });

            // 当用户选择省份时获取该省份对应的城市信息
            $('#provinceSelect').change(function () {
                // 获取所选省份的id
                var provinceId = $(this).val();

                // 清空城市列表和县区列表
                $('#citySelect').empty().append('<option value="">请选择城市</option>');
                $('#areaSelect').empty().append('<option value="">请选择县区</option>');

                // 如果没有选择省份,则不处理
                if (provinceId === '') {
                    return false;
                }

                // 发送AJAX请求获取所选省份对应的城市列表
                $.ajax({
                    url: 'city.php',
                    type: 'GET',
                    dataType: 'json',
                    data: { provinceId: provinceId },
                    success: function (data) {
                        // 循环添加城市列表
                        $.each(data, function (i, item) {
                            $('#citySelect').append('<option value="&#39; + item.id + &#39;">' + item.name + '</option>');
                        });
                    }
                });
            });

            // 当用户选择城市时获取该城市对应的县区信息
            $('#citySelect').change(function () {
                // 获取所选城市的id
                var cityId = $(this).val();

                // 清空县区列表
                $('#areaSelect').empty().append('<option value="">请选择县区</option>');

                // 如果没有选择城市,则不处理
                if (cityId === '') {
                    return false;
                }

                // 发送AJAX请求获取所选城市对应的县区列表
                $.ajax({
                    url: 'area.php',
                    type: 'GET',
                    dataType: 'json',
                    data: { cityId: cityId },
                    success: function (data) {
                        // 循环添加县区列表
                        $.each(data, function (i, item) {
                            $('#areaSelect').append('<option value="&#39; + item.id + &#39;">' + item.name + '</option>');
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>
Copy after login

After the page is run, users can select their provinces and cities through the drop-down list. When the user selects a province, an AJAX request is automatically sent to obtain the city list; when the user selects a city, an AJAX request is automatically sent to obtain the county list. Everything is completed without any page jumps, and the user experience is very good.

So far, we have successfully implemented the function of provincial-level linkage between PHP and AJAX. At the same time, we also feel the close collaboration between front-end and back-end technologies to bring users a better experience.

The above is the detailed content of How to use ajax in php to achieve provincial linkage. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!