


Implementation of three-level linkage between provinces and municipalities using picker in WeChat mini program
This article mainly introduces the relevant information on WeChat applet using picker to encapsulate the three-level linkage example code of provinces and municipalities. Friends in need can refer to the following
WeChat applet uses picker to encapsulate the three-level linkage of provinces and municipalities. Linkage Example
At present, learning mini programs is more about seeing whether other components can be encapsulated twice, which will help to quickly develop various mini program applications in the future. At present, it is found that the selector mode of picker only has one level of drop-down, so can we use three pickers to implement a three-level linkage template and introduce it to other pages? The answer is yes. Then my idea is this:
1. Use template template syntax for encapsulation, and the data is passed in from the page
2. According to the syntax of the picker component , range can only be a set of Chinese region arrays, but we need the unique code of each region to trigger the next level of linkage data. In this way, my approach is to store two object arrays of Chinese names and unique codes through two sets of data tables in one object. Format [province:{code:['110000', '220000'...], name: ['Beijing City', 'Tianjin City'...]}], this format is fixed and needs to be returned by the server.
3. Obtain the next level data through the bindchange event of the picker. Each method is written into the function and exposed for the page to call.
Then let’s talk about it The directory structure of my demo:
common
-net.js//wx.request request interface secondary integration
-cityTemplate.js//Three-level linkage method
page
-demo
-demo.js
-demo.wxml
template
-cityTemplate. wxml
app.js
app.json
app.wxss
Then, use phpstudy to build a simple server for testing. Don't ask me why the server side is like this, I don't understand either. I just want data when I'm just getting started...
Of course you can skip this step and fix the data directly in demo.js for testing. ..
The code is as follows: [The return data format of the server follows the retArr specification below]
<?php header("Content-type: text/html; charset=utf-8"); $type=$_REQUEST["type"];//获取省市区的标志 $fcode=$_GET["fcode"]; $retArr=[ "status"=>true, "data"=>[], "msg"=>"" ]; if($type!="province" && $type!="city" && $type!="county"){ $retArr["status"]=false; $retArr["msg"]="获取地区类型错误,请检查"; echo json_encode($retArr); exit; } function getProvince(){ $province=[]; $code=["110000", "350000", "710000"]; $province["code"]=$code; $name=["北京市", "福建省", "台湾省"]; $province["name"]=$name; $fcode=["0", "0", "0"]; $province["fcode"]=$fcode; return $province; } function getCity($P_fcode){ $city=[]; $code=[]; $name=[]; $fcode=[]; if($P_fcode=="110000"){ $code=["110100"]; $name=["北京市"]; $fcode=$P_fcode; } if($P_fcode=="350000"){ $code=["350100", "350200", "350300", "350400", "350500", "350600", "350700", "350800", "350900"]; $name=["福州市", "厦门市", "莆田市", "三明市", "泉州市", "漳州市", "南平市", "龙岩市", "宁德市"]; $fcode=$P_fcode; } if($P_fcode=="710000"){ } $city=["code"=>$code, "name"=>$name, "fcode"=>$fcode]; return $city; } function getCounty($P_fcode){ $county=[]; $code=[]; $name=[]; $fcode=[]; if($P_fcode=="110100"){ $code=["110101", "110102", "110103", "110104", "110105", "110106", "110107"]; $name=["东城区", "西城区", "崇文区", "宣武区", "朝阳区", "丰台区", "石景山区"]; $fcode=$P_fcode; } if($P_fcode=="350100"){ $code=["350102", "350103", "350104"]; $name=["鼓楼区", "台江区", "苍山区"]; $fcode=$P_fcode; } if($P_fcode=="350200"){ $code=["350203", "350205", "350206"]; $name=["思明区", "海沧区", "湖里区"]; $fcode=$P_fcode; } $county=["code"=>$code, "name"=>$name, "fcode"=>$fcode]; return $county; } //var_dump($province); if($type=="province"){ $province=getProvince(); $retArr["data"]=$province; }else if($type=="city"){ $city=getCity($fcode); $retArr["data"]=$city; }else if($type="county"){ $county=getCounty($fcode); $retArr["data"]=$county; } echo json_encode($retArr); ?>
Connect Down is cityTemplate.wxml::
<template name="city"> <view class="areas"> <view class="province"> <picker bindchange="provincePickerChange" value="{{provinceIndex}}" range="{{province.name}}" data-city-url="{{cityUrl}}"> <text class="select-item">{{province.name[provinceIndex]}}</text> </picker> </view> <view class="city"> <block wx:if="{{!city.name.length}}"> --二级市区-- </block> <block wx:if="{{city.name.length>0}}"> <picker bindchange="cityPickerChange" value="{{cityIndex}}" range="{{city.name}}" data-county-url="{{countyUrl}}"> <text class="select-item">{{city.name[cityIndex]}}</text> </picker> </block> </view> <view class="county"> <block wx:if="{{!county.name.length}}"> --三级地区-- </block> <block wx:if="{{county.name.length>0}}"> <picker bindchange="countyPickerChange" value="{{countyIndex}}" range="{{county.name}}"> <text class="select-item">{{county.name[countyIndex]}}</text> </picker> </block> </view> </view> </template>
cityTemplate.js::
/** * 获取三级联动的三个函数 * that: 注册页面的this实例 必填 * p_url: 一级省份url 必填 * p_data:一级省份参数 选填 */ var net = require( "net" );//引入request方法 var g_url, g_datd, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method; function initCityFun( that, p_url, p_data ) { //获取一级省份数据 g_cbSuccess = function( res ) { that.setData( { 'city.province': res }); }; net.r( p_url, p_data, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method ); //点击一级picker触发事件并获取市区方法 var changeProvince = function( e ) { that.setData( { 'city.provinceIndex': e.detail.value }); var _fcode = that.data.city.province.code[ e.detail.value ]; if( !_fcode ) { _fcode = 0; } var _cityUrl = e.target.dataset.cityUrl; g_url = _cityUrl + _fcode; g_cbSuccess = function( res ) { that.setData( { 'city.city': res }); } net.r( g_url, g_datd, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method ); }; that[ "provincePickerChange" ] = changeProvince; //点击二级picker触发事件并获取地区方法 var changeCity = function( e ) { that.setData( { 'city.cityIndex': e.detail.value }); var _fcode = that.data.city.city.code[ e.detail.value ]; if( !_fcode ) { _fcode = 0; } var _countyUrl = e.target.dataset.countyUrl; g_url = _countyUrl + _fcode; g_cbSuccess = function( res ) { that.setData( { 'city.county': res }); }; net.r( g_url, g_datd, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method ); }; that[ "cityPickerChange" ] = changeCity; //点击三级picker触发事件 var changeCounty = function( e ) { that.setData( { 'city.countyIndex': e.detail.value }); }; that["countyPickerChange"]=changeCounty; } function getProvinceFun(that, p_url, p_data){ g_cbSuccess = function( res ) { that.setData( { 'city.province': res }); }; net.r( p_url, p_data, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method ); } module.exports={ initCityFun: initCityFun, getProvinceFun: getProvinceFun }
Shun the net.js method::
/** * 网络发送http请求,默认为返回类型为json * * url: 必须,其他参数非必须 接口地址 * data:请求的参数 Object或String * successFun(dts):成功返回的回调函数,已自动过滤微信端添加数据,按接口约定,返回成功后的data数据,过滤掉msg和status * successErrorFun(msg):成功执行请求,但是服务端认为业务错误,执行其他行为,默认弹出系统提示信息. * failFun:接口调用失败的回调函数 * completeFun:接口调用结束的回调函数(调用成功、失败都会执行) * header:object,设置请求的 header , header 中不能设置 Referer * method:默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT * */ function r( url, data, successFun, successErrorFun, failFun, completeFun, header, method ) { var reqObj = {}; reqObj.url = url; reqObj.data = data; //默认头为json reqObj.header = { 'Content-Type': 'application/json' }; if( header ) { //覆盖header reqObj.header = header; } if( method ) { reqObj.method = method; } reqObj.success = function( res ) { var returnData = res.data; //将微信端结果过滤,获取服务端返回的原样数据 var status = returnData.status; //按接口约定,返回status时,才调用成功函数 //console.log(res); //正常执行的业务函数 if( status == true ) { if( successFun ) { var dts = returnData.data; successFun( dts );//回调,相当于获取到data后直接在回调里面处理赋值数据 } } else if( status == false ) { var msg = returnData.msg; if( !successErrorFun ) { console.log( msg ); } else { successErrorFun( msg ); } } else { console.log( "服务端没有按照接口约定格式返回数据" ); } } reqObj.fail = function( res ) { if( failFun ) { failFun( res ); } } reqObj.complete = function( res ) { if( completeFun ) { completeFun( res ); } } wx.request( reqObj ); } module.exports = { r: r }
The core code is the above three files, followed by the demo file for testing:
demo.wxml:
<import src="../../template/cityTemplate.wxml"/> <template is="city" data="{{...city}}" />
demo.js::
##
var city = require( '../../common/cityTemplate' ); Page( { data: { }, onLoad: function( options ) { var _that = this; //创建三级联动数据对象 ---- 这个city对象是固定的,只有请求的url是根据各自的服务端地址来更改的 _that.setData( { city: { province: {},//格式province:{code: ["11000", "12000"], name: ["北京市", "上海市"]},只能固定是name和code,因为模板需要根据这俩参数显示 city: {}, county: {}, provinceIndex: 0, cityIndex: 0, countyIndex: 0, cityUrl: "http://localhost:8282/phpserver/areas.php?type=city&fcode=",//type表示获取地区 fcode是一级code码,到时具体根据后端请求参数修改 countyUrl: "http://localhost:8282/phpserver/areas.php?type=county&fcode=" } }) var _url = "http://localhost:8282/phpserver/areas.php"; var _data = { 'type': 'province', 'fcode': '0' }; city.initCityFun( _that, _url, _data ); } })
The implementation of city selection by WeChat mini program imitating Meituan
The implementation of city positioning by WeChat mini program
The above is the detailed content of Implementation of three-level linkage between provinces and municipalities using picker in WeChat mini program. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

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

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to
