9.1 网络访问API
wx.request接口函数:参数为一个Object对象,有以下属性:
- url:开发者服务器接口地址
- data:
- header:设置请求的header,不能设置Referer
- method:请求的方法
- success:
- fail:
- complete:结束的回调函数
一个小程序同时只能有5个网络请求连接。
<!--pages/getweixin/getweixin.wxml-->
<view class="container">
<view class="btn-area">
<button type="primary" bindtap="getweixinTap">获取HTML数据</button>
</view>
<view class="wx_html">
<textarea value='{{html}}' style="width:95%;" auto-height maxlength="0" ></textarea>
</view>
</view>
data: {
html: 'fgsfg'
},
getweixinTap: function() {
var self = this;
wx.request( {
url: 'https://www.mprcdong.cn/',
data: { },
header: {
'Content-Type': 'application/json'
},
success: function(res) {
console.log(res);
self.setData({
html: res.data
})
}
})
},
9.2 手机归属地查询
通过网络接口获取JSON数据
手机归属地查询接口:http://apistore.baidu.com/(百度API集市)
<!--pages/phonehome/phonehome.wxml-->
<view class="page">
<view class="page_hd">
<text class="page_title">手机归属地查询</text>
</view>
<view class="section">
<input name="phone" placeholder="手机号码" bindinput="bindinput" />
<button type="primary" bindtap="phoneTap">查询</button>
</view>
<view class="pih_item" wx:if="{{errNum == 0}}">
<view class="pih_title">电话号码:{{phone}}</view>
<view class="pih_title">所属省份:{{province}}</view>
<view class="pih_title">所属城市:{{city}}</view>
<view class="pih_title">手机段号:{{prefix}}</view>
<view class="pih_title">运营商:{{supplier}}</view>
</view>
<view class="pih_item" wx:if="{{errMsg != ''}}">
<view class="err-msg">错误信息:{{errNum}} - {{errMsg}}</view>
</view>
</view>
data: {
phone: '', //
city: '',
prefix: '',
province: '',
suit: '',
supplier: '',
errMsg: '',
errNum:-2
},
bindinput: function(e) {
this.setData({
phone: e.detail.value, //更新手机号码
errMsg: '', //清空错误描述
errNum: -2 //错误码
})
},
phoneTap: function() {
var phone = this.data.phone;
if (phone != null && phone != "") {
var self = this;
//显示toast提示信息
wx.showToast({
title: "正在查询,请稍等...",
icon:"loading",
duration: 10000
});
wx.request({
url: "http://xxx.com/",
data: {
'phone': phone
},
header: {
'apikey': apiKey
},
success: function(res) {
wx.hideToast(); //隐藏toast
if (res.data.errNum == 0) {
self.setData({
errMsg: '',
errNum: res.data.errNum,
city: res.data.retData.city,
prefix: res.data.retData.prefix,
province: res.data.retData.province,
suit: res.data.retData.suit,
supplier: res.data.retData.supplier
})
} else {
self.setData({
errMsg: res.data.retMsg || res.data.errMsg,
errNum: res.data.errNum
})
}
}
})
}
},