原創聲明:本文為作者原創,未經允許不得轉載,經授權轉載需注明作者和出處
碼云地址: https://git.oschina.net/GreenLittleApple/wx_xiaochengxu01.git
先上圖
代碼解析
很簡單, 一個js就能搞定。
1、 顯示頁面
<!--index.wxml-->
<view class="body">
// 輸入框
<input type="number" maxlength="11" auto-focus class="phoneInput" bindinput="listenPhoneInput" />
// 查詢按鈕(bindtap點擊事件, 相當于onclick)
<button type="primary" bindtap="queryHome4Phone" class="btnQuery"> 查詢 </button>
// 結果顯示
<text class="result" wx:if="{{province != ''}}">
{{message}}
</text>
</view>
2、 控制代碼 js
// 監聽手機號輸入
listenPhoneInput: function(e) {
this.data.phoneNumber = e.detail.value
},
// 查詢手機號歸屬地
queryHome4Phone: function() {
var page = this
console.log("手機號是"+ this.data.phoneNumber)
// 網絡請求
wx.request({
url: 'http://apis.juhe.cn/mobile/get', // 接口地址
data: { // 參數
phone: this.data.phoneNumber,
key: '自己申請key(用的聚合數據)'
},
header: {
'Content-Type': 'application/json',
},
success: function(res) { // 成功回調函數
var result = res.data
console.log(res.data)
if(result.error_code == 201101) {
page.setData({
message: '手機號不能為空'
})
} else if(result.error_code == 201102) {
page.setData({
message: '錯誤的手機號碼'
})
} else if(result.error_code == 201103) {
page.setData({
message: '查詢無結果'
})
} else {
page.setData({ // 組合結果
message: result.result.province + " " + result.result.city + " " + result.result.company
})
}
}
})
},