在小程序中与后台交互数据用到的是wx.request;但是今天我用它来传递数据的时候,后台却得不到数据,
php:
header("Access-Control-Allow-Origin:*"); // 响应类型 header('Access-Control-Allow-Methods:POST'); // 响应头设置 header('Access-Control-Allow-Headers:x-requested-with, content-type'); function getData($key, $default = "") { return trim(isset($_REQUEST[$key])? $_REQUEST[$key]:$default ); } $tabName = getData("tabName"); var_dump($tabName);
我先用ajax进行调取,可以得到:
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button> 点击获取 </button> <p> </p> </body> <script src="http://g.ydbcdn.com/jquery/latest/jquery.min.js"></script> <script> $(() => { $("button").click(() => { $.ajax({ url:"http://fm.xiaofany.com/chart/chartsData.php", type:"post", data:{"tabName":"subject"}, dataType:"json", success:function (data) { console.log(data) } }) }) }) </script> </html>
可以得到我传递的参数
小程序的wxml:
wx.request({ url: "http://fm.xiaofany.com/chart/chartsData.php", data: {tabName:event.currentTarget.dataset.sub}, method:"POST", dataType:"json", success:function(res){ console.log(res.data) } })
结果跑并没有得到,原因是在传递的时候小程序需要写上头部信息:
header: { 'content-type': 'application/x-www-form-urlencoded' },
wx.request({ url: "http://fm.xiaofany.com/chart/chartsData.php", data: {tabName:event.currentTarget.dataset.sub}, header: { 'content-type': 'application/x-www-form-urlencoded' }, method:"POST", dataType:"json", success:function(res){ console.log(res.data) } })
这样就可以啦