RequestTask wx.request(Object object)

发起 HTTPS 网络请求。使用前请注意阅读相关说明

参数

Object object

属性类型默认值必填说明最低版本
urlstring开发者服务器接口地址
datastring/object/ArrayBuffer请求的参数
headerObject设置请求的 header,header 中不能设置 Referer。content-type 默认为 application/json
methodstringGETHTTP 请求方法
dataTypestringjson返回的数据格式
responseTypestringtext响应的数据类型1.7.0
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

object.method 的合法值

说明最低版本
OPTIONSHTTP 请求 OPTIONS
GETHTTP 请求 GET
HEADHTTP 请求 HEAD
POSTHTTP 请求 POST
PUTHTTP 请求 PUT
DELETEHTTP 请求 DELETE
TRACEHTTP 请求 TRACE
CONNECTHTTP 请求 CONNECT

object.dataType 的合法值

说明最低版本
json返回的数据为 JSON,返回后会对返回的数据进行一次 JSON.parse
其他不对返回的内容进行 JSON.parse

object.responseType 的合法值

说明最低版本
text响应的数据为文本
arraybuffer响应的数据为 ArrayBuffer

object.success 回调函数

参数
Object res
属性类型说明最低版本
datastring/Object/Arraybuffer开发者服务器返回的数据
statusCodenumber开发者服务器返回的 HTTP 状态码
headerObject开发者服务器返回的 HTTP Response Header1.2.0

返回值

RequestTask

基础库 1.4.0 开始支持,低版本需做兼容处理

请求任务对象

data 参数说明

最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:

  • 对于 GET 方法的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…
  • 对于 POST 方法且 header['content-type']application/json 的数据,会对数据进行 JSON 序列化
  • 对于 POST 方法且 header['content-type']application/x-www-form-urlencoded 的数据,会将数据转换成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…)

示例代码

  1. wx.request({
  2. url: 'test.php', //仅为示例,并非真实的接口地址
  3. data: {
  4. x: '',
  5. y: ''
  6. },
  7. header: {
  8. 'content-type': 'application/json' // 默认值
  9. },
  10. success (res) {
  11. console.log(res.data)
  12. }
  13. })