我目前正在尝试使用ajax从数据库(sql,phpmyadmin)发送一个2d数组。
我的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的二维数组
答案 0 :(得分: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
});
}
});