本文編輯: toBeMN瀏覽 35750
版權所有,嚴禁轉載
wx.request是小程序客戶端與服務器端交互的接口(類似javascript的ajax請求),只能發(fā)起 HTTPS 請求。一個微信小程序,同時只能有5個網(wǎng)絡請求連接,因此開發(fā)者要控制好請求的數(shù)量。由于request操作依賴網(wǎng)絡,會造成等待,影響用戶體驗,因此目前只支持異步模式。
需注意:
客戶端的 HTTPS TLS 版本為1.2,但 Android 的部分機型還未支持 TLS 1.2,所以請確保 HTTPS 服務器的 TLS 版本支持1.2及以下版本
請求參數(shù) method 的 value 經測試(IDE和IOS)不區(qū)分大小寫,默認為GET請求
小程序后臺(不是接口的后臺)配置的 URL 中不能帶有端口號,并且不能使用localhost/127.0.0.1
,想要在本地使用 localhost 進行測試,方法詳見下方提供的鏈接
利用request請求訪問微信小程序俱樂部提供的API
客戶端展示
服務器端展示
【代碼】
wxml
<view class="container">
<button hover-class="but-hover" bindtap="insert">插入數(shù)據(jù)</button>
<button hover-class="but-hover" bindtap="update">修改數(shù)據(jù)</button>
<button hover-class="but-hover" bindtap="del">刪除數(shù)據(jù)</button>
<text>key:{{aKey}}
value:{{aValue}}
type:{{aType}}</text>
</view>
js
var app = getApp()
Page({
data:{
aKey:"null",
aValue:"null",
aType:"null"
},
onLoad:function(options){
//加載時就獲取后臺的數(shù)據(jù)
this.get_data()
},
insert:function(){
// 插入數(shù)據(jù)
var that=this
wx.request({
url: 'https://api.wxappclub.com/put',
data: {
appkey: 'hi0yhmmemhkn00ud7ne748agga7qyj1j' ,
key: "akey",
value:"avalue",
type:"String"
},
method:'get',
header: {
'Content-Type': 'application/json'
},
success: function(res) {
that.get_data();
}
})
},
update:function(){
// 更新數(shù)據(jù)
var that=this
wx.request({
url: 'https://api.wxappclub.com/put',
data: {
appkey: 'hi0yhmmemhkn00ud7ne748agga7qyj1j' ,
key: "akey",
value:"new_avalue",
type:"String"
},
method:'get',
header: {
'Content-Type': 'application/json'
},
success: function(res) {
that.get_data();
}
})
},
del:function(){
//刪除數(shù)據(jù)
var that=this
wx.request({
url: 'https://api.wxappclub.com/del',
data: {
'appkey': 'hi0yhmmemhkn00ud7ne748agga7qyj1j' ,
'key': "akey",
'type':"String"
},
method:'get',
header: {
'Content-Type': 'application/json'
},
success: function(res) {
that.setData({
aKey:"null",
aValue:"null",
aType:"null"
})
}
})
},
get_data:function(){
// 獲取數(shù)據(jù)
var that=this;
wx.request({
url: 'https://api.wxappclub.com/get',
data: {
'appkey': 'hi0yhmmemhkn00ud7ne748agga7qyj1j',
'key': "akey",
'type':"String"
},
header: {
'content-type': 'application/json'
},
success: function(res) {
if(res.data.success){
that.setData({
aKey:res.data.result.key,
aValue:res.data.result.value,
aType:res.data.result.type
})
}
}
})
}
})
wxss
page{
height: 100%;
width:100%;
}
.container{
display: flex;
flex-direction: column;
align-items: center;
}
button{
width:500rpx;
margin: 10rpx 0;
}
.but-hover{
background-color: #5CB85C;
}
參數(shù)名 | 類型 | 必填 | 說明 |
---|---|---|---|
url | String | 是 | 請求后臺接口的地址(不能帶有端口號) |
data | Object、String | 否 | 請求攜帶的參數(shù) |
header | Object | 否 | 設置請求的 header , header 中不能設置 Referer |
method | String | 否 | 默認為 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT |
success | Function | 否 | 請求后臺成功返回后的回調函數(shù),res = {data: ‘開發(fā)者服務器返回的內容’} |
fail | Function | 否 | 接口調用失敗的回調函數(shù) |
complete | Function | 否 | 接口調用結束的回調函數(shù)(調用成功、失敗都會執(zhí)行) |