微信小程序之上傳下載交互api
阿新 • • 發佈:2017-07-06
數據轉換 ble 自定義函數 let component 回調 thead urlencode test
wx.request(OBJECT)
OBJECT參數說明:
參數名 | 類型 | 必填 | 說明 |
---|---|---|---|
url | String | 是 | 開發者服務器接口地址 |
data | Object、String | 否 | 請求的參數 |
header | Object | 否 | 設置請求的 header , header 中不能設置 Referer |
method | String | 否 | 默認為 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT |
dataType | String | 否 | 默認為 json。如果設置了 dataType 為 json,則會嘗試對響應的數據做一次 JSON.parse |
success | Function | 否 | 收到開發者服務成功返回的回調函數,res = {data: ‘開發者服務器返回的內容‘} |
fail | Function | 否 | 接口調用失敗的回調函數 |
complete | Function | 否 | 接口調用結束的回調函數(調用成功、失敗都會執行) |
success返回參數說明:
參數 | 說明 | 最低版本 |
---|---|---|
data | 開發者服務器返回的數據 | |
statusCode | 開發者服務器返回的狀態碼 | |
header | 開發者服務器返回的 HTTP Response Header | 1.2.0 |
data 數據說明 最終發送給服務器的數據是 String 類型,如果傳入的 data 不是 String 類型,會被轉換成 String 。轉換規則如下:
- 對於 header[‘content-type‘] 為 ‘application/json‘ 的數據,會對數據進行 JSON 序列化
- 對於 header[‘content-type‘] 為 ‘application/x-www-form-urlencoded‘ 的數據,會將數據轉換成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)
示例代碼:
wx.request({
url: ‘test.php‘, //僅為示例,並非真實的接口地址
data: {
x: ‘‘ ,
y: ‘‘
},
header: {
‘content-type‘: ‘application/json‘
},
success: function(res) {
console.log(res.data)
}
})
微信小程序開發時,使用公共的url端口,自定義函數
module.exports = {
// API 接口
API_HOST: "url/"
}
const config = require(‘../config.js‘);
module.exports = {
//get方式請求
GET: function (url = ‘‘, data = {}, fn) {
console.log(data);
wx.request({
url: config.API_HOST + url,//請求地址
method: ‘get‘,//請求方式
data: data,//請求參數
header: { "Content-Type": "application/x-www-form-urlencoded" },
success: function (res) {
fn(res);
}
});
},
//post方式請求
POST: function (url = ‘‘, data = {}, fn) {
wx.request({
url: config.API_HOST + url,//請求地址
method: ‘post‘,//請求方式
data: data,//請求參數
header: { "Content-Type":"application/x-www-form-urlencoded"},
success: function (res) {
fn(res);
}
});
},
}
微信小程序之上傳下載交互api