微信小程序网络请求 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')就搞定了。

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值