轉載: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