WeChat Web Development (7)--Query Network Status

Contents of this article

1. Background

You can use the Get Network Status interface to query the network status. The official interface description:

wx.getNetworkType({
    
    
  success: function (res) {
    
    
    var networkType = res.networkType; // 返回网络类型2g,3g,4g,wifi
  }
});

2. Code

First add the button:

<input type="button" value="网络状态" onclick="networkTest()"> |

Then write the method:

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. Debug

The result is obvious, currently using wifi.
insert image description here

Guess you like

Origin blog.csdn.net/woshisangsang/article/details/122682384