1. 程式人生 > >ajax中data引數json物件與json字串的使用區別

ajax中data引數json物件與json字串的使用區別

在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()轉換一下