1. 背景
可以使用获取网络状态接口,查询网络状态,官方接口说明:
wx.getNetworkType({
success: function (res) {
var networkType = res.networkType; // 返回网络类型2g,3g,4g,wifi
}
});
2. 代码
首先添加按钮:
<input type="button" value="网络状态" onclick="networkTest()"> |
然后编写方法:
var apiList = [ 'checkJsApi', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage','networkTest' ];
$(function() {
// 向后端请求配置信息
$.ajax({
type : "GET",
url : "/wx-server/wxJsapiSignature",
data : {
url : location.href.split('#')[0]
},
dataType : "json",
success : function(res) {
configInfo(res);
}
});
});
// 通过wx.config注入配置信息
function configInfo(res) {
wx.config({
debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId : res.appId, // 必填,公众号的唯一标识
timestamp : res.timestamp, // 必填,生成签名的时间戳
nonceStr : res.nonceStr, // 必填,生成签名的随机串
signature : res.signature,// 必填,签名
jsApiList : apiList
// 必填,需要使用的JS接口列表
});
// 处理成功后回调
wx.ready(function() {
console.log("处理成功:");
wx.checkJsApi({
jsApiList : apiList,
success : function(checkRes) {
console.log("checkRes:", checkRes);
}
});
});
// 处理失败后回调
wx.error(function(err) {
console.log("处理失败:", err);
});
}
// 网络状态
function networkTest() {
wx.getNetworkType({
success : function(res) {
console.log(res.networkType);// 返回网络类型2g,3g,4g,wifi
}
});
}
3. 调试
结果很明显,当前使用wifi。