16.小程序request請求

wx.request(OBJECT)

發起網絡請求。使用前請先閱讀說明javascript

OBJECT參數說明:php

參數名 類型 必填 默認值 說明 最低版本
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返回參數說明:html

參數 類型 說明 最低版本
data Object/String/ArrayBuffer 開發者服務器返回的數據  
statusCode Number 開發者服務器返回的 HTTP 狀態碼  
header Object 開發者服務器返回的 HTTP Response Header 1.2.0

data 數聽說明:java

最終發送給服務器的數據是 String 類型,若是傳入的 data 不是 String 類型,會被轉換成 String 。轉換規則以下:json

  • 對於 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)...)

示例代碼:api

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

示例代碼:app

const requestTask = wx.request({ url: 'test.php', //僅爲示例,並不是真實的接口地址 data: { x: '' , y: '' }, header: { 'content-type': 'application/json' }, success: function(res) { console.log(res.data) } }) requestTask.abort() // 取消請求任務

封裝請求:
相關文章
相關標籤/搜索