2014-05-16 80 views
1

我目前正試圖發送一個2d數組,我從ajax接收數據庫(sql,phpmyadmin)。我如何發送2d數組與Ajax?

我的AJAX功能如下:(這是在PHP中產生)

$.ajax({ 
     type: \"POST\", 
     url: \"resultQuizGet.php\", 
     data: \"getAnswer=\"+question+\"\", //question is just a int variable 
     success: function(msg) { 
      alert(\"Data Saved: \" + msg); 
      } 
}); 

我resultQuizGet.php文件,然後像

$sql = "SELECT `quiz`.question,`quiz`.rightAnswer 
FROM `quiz` 
WHERE `quiz`.quizID=:qID"; 
$stmt = $dbh->prepare($sql); 
$stmt->bindParam(":qID", $_POST['quiz']); 
$stmt->execute(); 
$resultsQuiz = $stmt->fetchAll(); 
echo ... 

什麼我現在要做的接收2d數組,而不僅僅是一個普通的字符串。

我想msg變量什麼是是一個二維數組,它是等於$ resultsQuiz

+2

在PHP中,如果它是一個數組,使用'json_encode'把它作爲一個結構數組到您的Ajax調用。然後,在您的jQuery中,使用'$ .parseJSON()'將其從json字符串轉換爲數組。 –

+0

我正在看它,但我dident使它的工作。我發現了一些關於json_encode()和JSON.stringify(),但couldent使其正常工作 –

回答

1

修改你的php如下,輸出數據作爲JSON格式的字符串:

$sql = "SELECT `quiz`.question,`quiz`.rightAnswer 
FROM `quiz` 
WHERE `quiz`.quizID=:qID"; 
$stmt = $dbh->prepare($sql); 
$stmt->bindParam(":qID", $_POST['quiz']); 
$stmt->execute(); 
$resultsQuiz = $stmt->fetchAll(); 
echo json_encode($resultsQuiz); 

然後,修改您的jQuery如下解析該結構化的字符串返回到一個數組/對象:

$.ajax({ 
     type: "POST", 
     url: "resultQuizGet.php", 
     data: "getAnswer="+question, //question is just a int variable 
     success: function(msg) { 
      // Note: if it's not json, this can cause a problem 
      var data = $.parseJSON(msg); 
      // output to your console so you can see the structure 
      console.log(data); 
      // Utilize the data somehow 
      $.each(data, function(key, arr) { 
       // Arr should contain an object/array representing the rows from your php results 
       console.log(arr); 
       // If your row has a field titled `question`, you can access it one of two ways: 
       alert(arr.question); // Object notation 
       alert(arr['question']); // Array notation 
      }); 
     } 
}); 
+0

+1 ...好的回答:) – Hackerman

+0

我試過這個,但我couldent繼續如何從這裏得到2d數組 –

+0

@RobinAndersson - 查看我的修訂。有趣的你問,因爲我正在編輯,以顯示這之前,你的評論進來... –