>  기사  >  백엔드 개발  >  PHP와 UniApp을 통해 데이터의 다단계 연결을 달성하는 방법

PHP와 UniApp을 통해 데이터의 다단계 연결을 달성하는 방법

WBOY
WBOY원래의
2023-07-04 15:36:10774검색

PHP 및 UniApp을 통해 데이터의 다단계 연결을 구현하는 방법

소개:
웹 애플리케이션 및 모바일 애플리케이션을 개발할 때 지방 및 도시 선택, 선택 등 다단계 연결을 구현해야 하는 경우가 종종 있습니다. 제품 카테고리 등을 기다려주세요. 이 기사에서는 PHP와 UniApp을 사용하여 데이터의 다단계 연결을 달성하는 방법을 소개하고 해당 코드 예제를 제공합니다.

1. 데이터 준비
시작하기 전에 먼저 다단계 연계에 필요한 데이터를 준비해야 합니다. 지방자치단체의 3단계 연결을 위한 선택기를 구현한다고 가정하면, 지방자치단체에 대한 데이터 테이블을 준비해야 합니다.

지방 테이블(지방 테이블):
id name
1 지방 1
2 지방 2
...

city 테이블(도시 테이블):
id 지방 ID 이름
1 1 도시 1
2 1 도시 2
3 2 City 3
4 2 City 4
...

지역 테이블(면적 테이블):
id city_id name
1 1 Area 1
2 1 Area 2
3 2 Area 3
4 2 Area 4
...

2. PHP 측 구현

  1. getData.php라는 PHP 파일을 생성하여 프런트 엔드 요청을 처리하고 해당 데이터를 반환합니다.

969a660379cf442611bd66a68707c1f6exec('set names utf8');

// 지역 데이터 가져오기
$provinces = $pdo->query('지역에서 * 선택' ) ->fetchAll(PDO::FETCH_ASSOC);

// 지방 ID를 기준으로 해당 도시 데이터를 가져옵니다.
if (isset($_GET['province_id'])) {

$provinceId = $_GET['province_id'];
$cities = $pdo->query("select * from cities where province_id = $provinceId")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($cities);

}

// Get 도시 ID를 기준으로 해당 도시 데이터 해당 지역 데이터
if (isset($_GET['city_id'])) {

$cityId = $_GET['city_id'];
$areas = $pdo->query("select * from areas where city_id = $cityId")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($areas);

}
?>

  1. UniApp 프로젝트에서 MultiLevelLinkage라는 페이지를 생성하여 표시합니다. 다단계 연결 선택기.

ca9ceec3554d5f69281718c4b9ecdc8b

<view class="container">
    <picker mode="selector" range-key="name" range="{{provinces}}" bind:change="onChangeProvince">
        <view class="picker">
            {{province}}
        </view>
    </picker>
    
    <picker mode="selector" range-key="name" range="{{cities}}" bind:change="onChangeCity">
        <view class="picker">
            {{city}}
        </view>
    </picker>
    
    <picker mode="selector" range-key="name" range="{{areas}}">
        <view class="picker">
            {{area}}
        </view>
    </picker>
</view>

21c97d3a051048b8e55e3c8f199a54b2

3f1c4e4b6b16bbbd69b2ee476dc4f83a

export default {
    data() {
        return {
            province: '',   // 省份
            city: '',       // 城市
            area: '',       // 区域
            provinces: [],  // 省份数据
            cities: [],     // 城市数据
            areas: []       // 区域数据
        }
    },
    mounted() {
        this.getProvinces()
    },
    methods: {
        // 获取省份数据
        getProvinces() {
            uni.request({
                url: 'http://localhost/getData.php',
                success: (res) => {
                    this.provinces = res.data
                }
            })
        },
        // 根据省份ID获取对应的城市数据
        getCities(provinceId) {
            uni.request({
                url: 'http://localhost/getData.php?province_id=' + provinceId,
                success: (res) => {
                    this.cities = res.data
                }
            })
        },
        // 根据城市ID获取对应的区域数据
        getAreas(cityId) {
            uni.request({
                url: 'http://localhost/getData.php?city_id=' + cityId,
                success: (res) => {
                    this.areas = res.data
                }
            })
        },
        // 省份选择器变化时的事件
        onChangeProvince(event) {
            const index = event.detail.value
            this.province = this.provinces[index].name
            this.city = ''
            this.area = ''
            this.getCities(this.provinces[index].id)
        },
        // 城市选择器变化时的事件
        onChangeCity(event) {
            const index = event.detail.value
            this.city = this.cities[index].name
            this.area = ''
            this.getAreas(this.cities[index].id)
        }
    }
}

2cacc6d41bbb37262a98f745aa00fbf0

c9ccee2e6ea535a969eb3f532ad9fe89

.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
}

.picker {
    padding: 10px;
    border: 2px solid #ddd;
    border-radius: 4px;
    background-color: #f5f5f5;
    margin-bottom: 20px;
}

531ac245ce3e4fe3d50054a55f265927

3. 요약
합격 위의 예에서 우리는 PHP와 UniApp을 사용하여 다단계 데이터 연결을 달성하는 것이 복잡하지 않다는 것을 알 수 있습니다. PHP 측의 데이터 처리와 UniApp 측의 페이지 작성을 통해 단 몇 줄의 코드만으로 간단하고 실용적인 다단계 연결 선택기를 구현할 수 있습니다. 이 기사가 다단계 데이터 연결에 대한 요구를 실현하는 데 도움이 되기를 바랍니다.

위 내용은 PHP와 UniApp을 통해 데이터의 다단계 연결을 달성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.