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 | object/string/arraybuffer | 开发者服务器返回的数据 | |
statuscode | number | 开发者服务器返回的 http 状态码 | |
header | object | 开发者服务器返回的 http response header | 1.2.0 |
示例代码:
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '' ,
y: ''
},
header:{
"content-type":"application/json"
},
success: function(res) {
console.log(res.data)
}
})
返回值:
基础库 1.4.0 开始支持,低版本需做兼容处理
返回一个requesttask
对象,通过requesttask
,可中断请求任务。
requesttask 对象的方法列表:
方法 | 参数 | 说明 | 最低版本 |
---|---|---|---|
abort | 中断请求任务 | 1.4.0 |
示例代码:
const requesttask = wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json'
},
success: function(res) {
console.log(res.data)
}
})
requesttask.abort() // 取消请求任务
tip
: content-type 默认为 'application/json'bug
: 开发者工具0.10.102800
版本,header
的content-type
设置异常;tip
: 客户端的 https tls 版本为1.2,但android
的部分机型还未支持 tls 1.2,所以请确保 https 服务器的 tls 版本支持1.2及以下版本;tip
: 要注意 method 的 value 必须为大写(例如:get);tip
: url 中不能有端口;tip
: request 的默认超时时间和最大超时时间都是 60stip
: request 的最大并发数是 5tip
: 网络请求的 referer 是不可以设置的,格式固定为 https://servicewechat.com/{appid}/{version}/page-frame.html,其中{appid}
为小程序的 appid,{version}
为小程序的版本号,版本号为 0 表示为开发版。