網絡請求,基本上是必須的環節之一。
小程序提供了wx.request(object),與開發者的服務器實現數據交互的一個很重要的api。
最簡單的用法如下(以GET請求爲例)
<view bindtap="bindSearchChange"><view>
bindSearchChange:function(){
wx.request({
method:"GET", //注意請求方式必須要大寫!!!
url:'xxxxxxxxx',
data:{},
header: {'content-type': 'application/json'}, //content-type必須要小寫!!!
success: function(res) {
console.log(res)
}
})
}
完整示例:
下面我們把請求寫在service文件下的http.js文件中,代碼如下
var root = 'hxxxxx';//你的域名
function req(url,data,cb){
wx.request({
url: root + 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 () {
//dosomething
},
func:{
req:http.req
}
})
這時這個req就是全局的了,在調用時我們可以使用getApp.func.req()來調用,具體如下
var app = getApp()
Page({
data: {
},
onLoad: function (opt) {
app.func.req('/api/get_data',{},function(res){
console.log(res)
});
}
})
目前,小程序還有待完善
其中在網絡請求上,還需要注意一些細節:
1> method請求方式,必須要使用大寫的GET或POST!!
2> content-type,必須要使用小寫,使用大寫不能正常發起請求!!