前端:小程序
接口: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')
就搞定了。