-- 時常在想,怎么樣才能把知識寫的清晰,其實是我理解的不夠清晰
微信小程序其實是一個客戶端頁面,也是需要和服務器交互才能體現數據。
1 --服務器搭建Web API :MVC4 中的一個模板, 如下是Query API 的一個Get 方式,只是為了了解 JsonConvert.SerializeObject(_dt.ToList()); 值如何返回到界面
1 #region --- 查詢綁定信息 --- 2 [HttpGet] 3 public string GetQuery(string strEcNo) 4 { 5 //查詢此EC單是否被綁定過 6 try 7 { 8 PcdbE.PcdbDataContext _Pc = new PcdbE.PcdbDataContext(); 9 10 var _dt = from s in _Pc.EcDressLogs 11 where s.EcNo == strEcNo 12 select s; 13 14 var _count = _dt.Count(); 15 16 if(_count.Equals(0)) 17 { 18 return "沒有綁定記錄"; 19 } 20 21 return JsonConvert.SerializeObject(_dt.ToList()); 22 } 23 catch (Exception) 24 { 25 return "error"; 26 } 27 28 } 29 #endregion
2 -- 客戶端如何Call 個API ,先要在小程序管理員去注冊API 發布的服務器域名, https:// 這部分,好像之前做過了
BtnQuery 是綁定給界面的一個方法,在.wxml文件中
1 <!--按鈕--> 2 <view class="loginBtnView"> 3 <button type="primary" bindtap="BtnQuery"> Query </button> 4 </view>
3 -- 在.js 文件中
1 BtnQuery: function (){ 2 if (this.data.ecno.length == 0) 3 { 4 wx.showToast({ 5 title: '不能為空', 6 icon: 'loading', 7 duration: 2000 8 }) 9 10 }else{ 11 12 wx.request({ 13 method: "GET", 14 url: 'https://(這里是你在微信小程序注冊的你發布的API 域名)/api/pc/GetQuery', //僅為示例,並非真實的接口地址 15 data: { 16 strEcNo: this.data.ecno 17 }, 18 header: { 19 'content-type': 'application/json' // 默認值 20 }, 21 success: (res) => { 22 this.setData({ 23 warning: res.data 24 }) 25 var result = JSON.parse(res.data); 26 if(res.data !="") 27 { 28 console.log(result) 29 } 30 var x = result[0].Xdress 31 var y = result[0].Ydress 32 wx.navigateTo({ url: '/pages/tzdress/tzdress?xdress='+x+'&ydress='+y}) 33 } 34 35 }) 36 37 38 } 39 },
主要的部分還是succes 返回里面的數據格式, 由於在API 中返回的是list ,我這里因為只有一個數據,所以取得是list里面第一個位置,當然如果是list表數據多,就需要寫循環的方式了, 而最后面的wx.navigateTo 是為了在微信小程序客戶端進行,頁面跳轉使用的,並傳遞了,值
4 -- 那么問題來了:
wx.navigateTo({ url: '/pages/tzdress/tzdress?xdress='+x+'&ydress='+y})
傳遞的值,在對應頁面又如何的接收?
對應就需要到tzdress.js文件中去看, onLoad 是小程序頁面的生命周期中的一個頁面加載部分,頁面加載時執行, 而值傳遞,值都是在options中的。
所以取值就是options.xdress 參數名稱即可
1 onLoad: function (options) { 2 3 var _this = this; 4 wx.getSystemInfo({ 5 success: function (res) { 6 _this.setData({ 7 view: { 8 Height: res.windowHeight - 150 9 }, 10 longitude: options.xdress, 11 latitude: options.ydress, 12 circles: [{ 13 latitude: options.ydress, 14 longitude: options.xdress, 15 color: '#FF0000DD', 16 fillColor: '#7cb5ec88', 17 radius: 3000, 18 strokeWidth: 1 19 20 }] 21 }) 22 } 23 }) 24 }
