1. 程式人生 > >微信小程式網路請求 wx.request() ,data內參數後臺獲取不到

微信小程式網路請求 wx.request() ,data內參數後臺獲取不到

前端:小程式
介面:thinkphp3.2.3
問題描述:如果小程式設定 method:’POST’,後臺 I()無法獲取前端傳參

解決方案一:
小程式:不設定 mothod,小程式預設用’GET’,
後臺:I() 正常獲取前端傳參

小程式 .js程式碼

wx.request({
    url: 'http://api.zhipur.com/test',//換成實際介面地址
    data: {id:1},
    success: function(res){
       console.log('id from server is: '+res.data);// 控制檯顯示 1
    }
 })

後臺介面 程式碼

public function test(){
    $id = I('id');// 結果: $id = 1
    exit($id);//為方便展示,用exit()
}

解決方案二:
小程式: 只設置 method
介面:通過 file_get_contents(‘php://input’) 取值

小程式 .js程式碼

wx.request({
    url: 'http://api.zhipur.com/test',
    data: { id: 1},
    method: 'POST',
    header: { 'content-type': 'application/x-www-form-urlencoded' }
, success: function(res){ console.log(res.data); } })

後臺介面 程式碼

public function test(){
    $request = file_get_contents('php://input');
    $arr = json_encode($request,true);
    $id = $arr['id'];
    exit($id);
}

具體原因請看小程式的說明:

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

解決方案三:
小程式: 同時指定 mothod:'POST'header: {}
後臺: 直接通過 I() 獲取到前端傳參

微信小程式前端程式碼:

//同時設定 method 和 header
wx.request({
    url: 'http://api.zhipur.com/test',
    data: { id: 1},
    method: 'POST',
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    success: function(res){
       console.log(res.data); 
    }
 })

後臺程式碼就不寫了,一個 I('id')就搞定了。