在jquery的ajax里面有个data参数,是客户的传给服务端的数据
我们先看第一种常见写法:
前端代码:
var username = $('#phone_email_num').val();
var pwd = $('#password').val();
$.ajax({
url : 'login.php',
type : 'post',
data : {username:username,pwd:pwd}, //这里是json对象
success : function(data){......}
)};
后端代码:
我们打印post过来的值
dump($_POST);
结果:
Array
(
[username] => 18711111111
[pwd] => 123456
)
我们再看第二种写法:
前端代码
$.ajax({
url : 'login.php',
type : 'post',
data : JSON.stringify({a: 'a', b: 'b'}), //这个是json字符串
contentType: 'application/json', //规定传的值是json
success : function(data){...}
)};
后端代码:
这个时候dump($_POST);其结果:
Array
(
)
什么也没有,我们可以使用如下方法:
$_POST = json_decode(file_get_contents('php://input'), true);
再dump($_POST);其结果:
Array
(
[a] => a
[b] => b
)
第一种情况的ajax默认是以application/x-www-form-urlencoded方式提交。也就是常见的表单提交方式。在PHP中使用$_POST方式可以轻松获取,如果使用ajax的application/json方式,记得data参数是字符串类型的。使用JSON.stringify()转换一下
参考:https://blog.csdn.net/m0_37572458/article/details/78622668?locationNum=6&fps=1
https://www.cnblogs.com/CyLee/p/7644380.html
https://segmentfault.com/a/1190000014126990?utm_source=index-hottest