ajax中data参数json对象与json字符串的使用区别

转载:https://blog.csdn.net/u011280342/article/details/79789379

在jquery的ajax里面有个data参数,是客户的传给服务端的数据 
我们先看第一种常见写法:

 1 前端代码:
 2   var username = $('#phone_email_num').val();
 3   var pwd = $('#password').val();
 4   $.ajax({
 5          url : 'login.php',
 6          type : 'post',
 7          data : {username:username,pwd:pwd},  //这里是json对象
 8          success : function(data){......}
 9    )};
10 
11 后端代码:
12 我们打印post过来的值
13 dump($_POST);
14 结果:
15 Array
16 (
17     [username] => 18711111111
18     [pwd] => 123456
19 )

我们再看第二种写法:

前端代码
$.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

猜你喜欢

转载自www.cnblogs.com/nb123/p/12159811.html
今日推荐