Home > WeChat Applet > Mini Program Development > Implementation of three-level linkage between provinces and municipalities using picker in WeChat mini program

Implementation of three-level linkage between provinces and municipalities using picker in WeChat mini program

不言
Release: 2018-06-27 16:19:30
Original
7192 people have browsed it

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); 
 
 
?>
Copy after login

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>
Copy after login

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( { 
    &#39;city.province&#39;: 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( { 
      &#39;city.provinceIndex&#39;: 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( { 
        &#39;city.city&#39;: 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( { 
      &#39;city.cityIndex&#39;: 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( { 
        &#39;city.county&#39;: 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( { 
      &#39;city.countyIndex&#39;: e.detail.value 
    }); 
  }; 
  that["countyPickerChange"]=changeCounty; 
} 
 
function getProvinceFun(that, p_url, p_data){ 
  g_cbSuccess = function( res ) { 
   that.setData( { 
    &#39;city.province&#39;: 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 
}
Copy after login

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 = { &#39;Content-Type&#39;: &#39;application/json&#39; }; 
  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 
}
Copy after login

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}}" />
Copy after login

demo.js::

##

var city = require( &#39;../../common/cityTemplate&#39; ); 
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 = { &#39;type&#39;: &#39;province&#39;, &#39;fcode&#39;: &#39;0&#39; }; 
  city.initCityFun( _that, _url, _data ); 
 } 
})
Copy after login

The above complete code file, the final test is as follows:

There is a bug here. The pull-down refresh and the pull-down of the picker component will overlap. I don’t know if it is due to the development tools or a bug that needs to be modified. . . I can only wait for WeChat to update the news and give feedback

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

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!

Related labels:
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