微信小程序> 微信小程序网络请求wx.request(),data内参数后台获取不到

微信小程序网络请求wx.request(),data内参数后台获取不到

浏览量:524 时间: 来源:武当山道士

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

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

最新资讯

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎