微信小程式網路請求wx.request請求
阿新 • • 發佈:2019-01-05
最近微信小程式開始開放測試了,小程式提供了很多api,極大的方便了開發者,其中網路請求api是wx.request(object),這是小程式與開發者的伺服器實現資料互動的一個很重要的api。
大家可以先看官方文件微信小程式API
再給大家提供一個開發工具下載地址小程式開發工具
最簡單的用法如下(以POST請求為例)
bindSearchChange:function(e){
var keyword = e.detail.value;
wx.request({
url:'xxxxxxxxx',
data:{},
header: {'Content-Type' : 'application/json'},
success: function(res) {
console.log(res)
}
})
}
下面我們把請求寫在service檔案下的http.js檔案中,程式碼如下
var rootDocment = 'hxxxxx';//你的域名
function req(url,data,cb){
wx.request({
url: rootDocment + url,
data: data,
method: 'post' ,
header: {'Content-Type': 'application/json'},
success: function(res){
return typeof cb == "function" && cb(res.data)
},
fail: function(){
return typeof cb == "function" && cb(false)
}
})
}
module.exports = {
req: req
}
其中module.exports是將req方法暴露出去使得別的檔案中可以使用該方法,由於js函式是非同步執行的,所以return 的是回撥函式,而不是具體的資料
為了其他檔案方便呼叫此方法,我們在根目錄的app.js檔案中將其註冊成為全域性函式,如下
//app.js
var http = require('service/http.js')
App({
onLaunch: function () {
//呼叫API從本地快取中獲取資料
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
},
getUserInfo:function(cb){
var that = this
if(this.globalData.userInfo){
typeof cb == "function" && cb(this.globalData.userInfo)
}else{
//呼叫登入介面
wx.login({
success: function () {
wx.getUserInfo({
success: function (res) {
that.globalData.userInfo = res.userInfo
typeof cb == "function" && cb(that.globalData.userInfo)
}
})
}
})
}
},
globalData:{
userInfo:null
},
func:{
req:http.req
}
})
這時這個req就是全域性的了,在呼叫時我們可以使用getApp.func.req()來呼叫,具體如下
var app = getApp()
Page({
data: {
},
onLoad: function (opt) {
//console.log(opt.name)
app.func.req('/api/get_data',{},function(res){
console.log(res)
});
}
})