1. 程式人生 > >微信小程式開發之網路請求(GET請求)

微信小程式開發之網路請求(GET請求)

微信小程式開發中網路請求必不可少,今天說說最簡單的請求.後續會嘗試上傳下載,Socket這些.

1.一個微信小程式,同時只能有5個網路請求連線。

這個規定應該是微信為了保證使用者體驗制定的,畢竟是小程式.

2.wx.request(OBJECT)  引數說明:


微信小程式支援GET,POST等請求.用method可以設定.

以下是GET請求的程式碼:

<span style="font-size:18px;">//rate.js
//獲取應用例項
var app = getApp()
Page( {
  data: {
    code: 'USD',
    currencyF_Name: '',
    currencyT_Name: '',
    currencyF: '',
    currencyT: '',
    currencyFD: 1,
    exchange: 0,
    result: 0,
    updateTime: '',
  },
  onLoad: function( options ) {
    var that = this;
      //獲取匯率
      wx.request( {
        url: "http://op.juhe.cn/onebox/exchange/currency?key=我的appkey&from=CNY&to="+code,
        success: function( res ) {
          that.setData( {
            currencyF_Name: res.data.result[0].currencyF_Name,
            currencyT_Name: res.data.result[0].currencyT_Name,
            currencyF: res.data.result[0].currencyF,
            currencyT: res.data.result[0].currencyT,
            currencyFD: res.data.result[0].currencyFD,
            exchange: res.data.result[0].exchange,
            result: res.data.result[0].result,
            updateTime: res.data.result[0].updateTime,
          })
        }
      })
  }
})</span>
上面程式碼中只需要給出URL即可,onLoad函式在頁面初始化時啟動,wx.request({})中success的res.data是從後臺獲取的資料,這一點需要注意.

以下是獲取的json資料的格式.


json的解析都不需要自己做了.我做android的時候還得用gson或者是fastjson來解析json.

微信為我們解決了很多麻煩.

http://blog.csdn.net/qq_31383345