• 16.小程序request请求


    wx.request(OBJECT)

    发起网络请求。使用前请先阅读说明

    OBJECT参数说明:

    参数名类型必填默认值说明最低版本
    url String   开发者服务器接口地址  
    data Object/String/ArrayBuffer   请求的参数  
    header Object   设置请求的 header,header 中不能设置 Referer。  
    method String GET (需大写)有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT  
    dataType String json 如果设为json,会尝试对返回的数据做一次 JSON.parse  
    responseType String text 设置响应的数据类型。合法值:text、arraybuffer 1.7.0
    success Function   收到开发者服务成功返回的回调函数  
    fail Function   接口调用失败的回调函数  
    complete Function   接口调用结束的回调函数(调用成功、失败都会执行)

    success返回参数说明:

    参数类型说明最低版本
    data Object/String/ArrayBuffer 开发者服务器返回的数据  
    statusCode Number 开发者服务器返回的 HTTP 状态码  
    header Object 开发者服务器返回的 HTTP Response Header 1.2.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)...)

    示例代码:

    wx.request({
      url: 'test.php', //仅为示例,并非真实的接口地址
      data: {
         x: '' ,
         y: ''
      },
      header: {
          'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log(res.data)
      }
    })
    

    返回一个 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() // 取消请求任务

    封装请求:

  • 相关阅读:
    在一个类中写完多线程(sleep 方法和wait 方法的区别)
    final
    Oracle 远程访问配置
    在 Windows Forms 和 WPF 应用中使用 FontAwesome 图标
    C#反序列化XML异常:在 XML文档(0, 0)中有一个错误“缺少根元素”
    C#[Win32&WinCE&WM]应用程序只能运行一个实例:MutexHelper
    『.NET Core CLI工具文档』(十四)dotnet-install 脚本参考
    『.NET Core CLI工具文档』(十三)dotnet-publish
    『.NET Core CLI工具文档』(十二)dotnet-pack
    『.NET Core CLI工具文档』(十一)dotnet-test
  • 原文地址:https://www.cnblogs.com/kai-z/p/8512277.html
Copyright © 2020-2023  润新知