2016-11-23 156 views
0

我填補像這樣的數組:Ajax:將數組正確發送到php?

JS

playersDone["gk"] = "test"; 
playersDone["df1"] = "test2"; 

和我AJAX部分看起來是這樣的:

$.ajax({ 
    url:'writeDraftedTeamToDraftsDatabase.php', 
    type:'post', 
    data:{players: JSON.stringify(playersDone)}, 

    success: function (res) {       
     alert(res);      
    } 
}); 

和我PHP樣子這個:

echo $_POST['players']['gk']; 

但是用這種方法我不能正確地獲得我的數組元素的值!

就像你看到的我已經試圖用JSON.stringify()傳遞數組,但沒有成功!

你可能會給我一個提示,我的錯誤在哪裏?

非常感謝!

+0

爲什麼當AJAX方法已經序列化PHP的數據時調用JSON.stringify? – zzzzBov

+0

因爲我從另一個stackoverflow問題中得到了這個... – nbg15

回答

0

確定這裏是我的解決方案:

JS/AJAX

var playersDone = {}; // THIS IS IMPORTANT, not var playersDone = [] becasue js works with objects not with assoc. arrays !!! 

$.ajax({ 
      url:'writeDraftedTeamToDraftsDatabase.php', 
      type:'post', 
      data:{'players':playersDone}, 
      success: function (res) {       
       alert(res);       
      } 
     }); 

PHP

$data = $_POST['players'];  
echo json_encode($data); 

編輯:一個也是一個很好的辦法是使用webDevelopsers工具的Firefox來檢查Ajax請求標頭,因爲在那之後我發現我的請求con帳篷是空的...;),我知道「確定空字符串被髮送」在js /客戶端有問題!