Php 如何使用ajax发送2d数组?
我目前正在尝试用ajax发送一个从数据库(sql,phpmyadmin)接收的2d数组 我的ajax函数如下所示:(它是用php生成的) 我的resultQuizGet.php文件如下所示Php 如何使用ajax发送2d数组?,php,jquery,ajax,arrays,Php,Jquery,Ajax,Arrays,我目前正在尝试用ajax发送一个从数据库(sql,phpmyadmin)接收的2d数组 我的ajax函数如下所示:(它是用php生成的) 我的resultQuizGet.php文件如下所示 $sql = "SELECT `quiz`.question,`quiz`.rightAnswer FROM `quiz` WHERE `quiz`.quizID=:qID"; $stmt = $dbh->prepare($sql); $stmt->bindParam(":qID", $
$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数组,它等于$resultsquick修改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
});
}
});
在php中,如果是数组,则使用
json\u encode
将其作为结构化数组传递给ajax调用。然后,在jQuery中,使用$.parseJSON()
将其从json字符串转换为数组。我发现了一些关于json_encode()和json.stringify()的信息,但无法使其正常工作。我尝试过这一点,但无法继续了解如何从here@RobinAndersson-见我的修订。你问的很有趣,因为在你的评论出现之前,我正在编辑以显示这一点。。。
$.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
});
}
});