微信小程序的 wx.request 請求,method 設為 POST 並向后台傳遞數據,但從后台返回的信息來看后台並沒有獲得傳遞的數據
wx.request({ url: url, //僅為示例,並非真實的接口地址 data: params, method: 'POST', header: { 'content-type': 'application/json' // 默認值 }, success: function(res) { options.onSuccess(res) }, fail: function(res) { options.onError(res) } })
用的 CI 框架,框架內部封裝了獲取 $_GET 和 $_POST 全局變量的方法,一開始懷疑是不是參數不符合標准,然后被內部過濾掉了。
本地測試:
GET 請求 ok,本地用 ajax POST 數據也能拿到,所以排除框架自身原因,百度了一下,其他博客里強調的都是同一件事,看小程序的文檔。
小程序的 wx.request 是針對 ajax 的一種封裝,封裝之后是有些特性變化的。
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)...)
也就是說 POST 請求,服務器端是拿不到字段的,只能直接取 $_POST, 然后 JSON 解析出具體數據。POST + application/x-www-form-urlencoded
作為正常的表單提交數據,被改成了 GET 方法提交。。。
好吧,不服不行!
也提醒自己一點: