小程序 wx.request请求

1.wx.request相当于发送ajax请求

微信官方解释

参数

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

object.dataType 的合法值

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

object.success 回调函数

参数

Object res

属性类型说明
datastring/Object/Arraybuffer开发者服务器返回的数据
statusCodenumber开发者服务器返回的 HTTP 状态码
headerObject开发者服务器返回的 HTTP Response Header

示例代码

wx.request({
  url: 'http://127.0.0.1:8000/test/', // 仅为示例,并非真实的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  method:'POST' //发送post请求
  success(res) {
    console.log(res.data)
  }
})