我目前正试图发送一个2d数组,我从数据库(sql, phpmyadmin)与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变量是一个2d数组,等于$resultsQuiz
按如下方式修改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
});
}
});