0

我正在尝试通过 jQuery、Ajax 和 PHP 从 SQL 数据库中获取数据。

这是jQuery代码

$.ajax({
    url: 'OpenQuiz.php',
    data: '',
    dataType:'json',
    success: function(data) {
        var one = data[0];
    }
}

$(document).ajaxComplete(function(event,request,settings) {
    alert("check");
}

这是名为“OpenQuiz.php”的 PHP 文件末尾的 json 编码行

echo json_encode($QuizName);
echo json_encode($options);
echo json_encode($votes);
echo json_encode($row_num);
echo json_encode($percentage);
echo json_encode($TruncPercentage);

请注意:$options、$votes、$Percentage 和 $TruncPercentage 都是二维数组。$row_num 是一个整数。$Quiz_Name 是一维数组。

我发现 jQuery 运行良好并且调用了 ajax 请求,因为“检查”的警报框出现了。问题是我不知道如何在变量转移后访问它们。我知道它与 data[0] 有关,但我真的不明白“data[0]”是什么意思或它代表什么。基本上如何访问我在 PHP 文件中使用 json_encode 发送的变量?

4

1 回答 1

1

data[0] is the first json_encoded item in the array returned. You shouldn't json_encode everything separately, you should build an array and json_encode this.

$items = array('QuizName'=>$QuizName,'options'=>$options, ... ,'TruncPercentage'=>$TruncPercentage);

echo json_encode($items);

Then you retrieve with:

success: function(data) {
    var qn = data.QuizName,
        opt = data.options;
}

And so on for each item, with data.[whatever], and [whatever] being the name of the item you gave it in the array. I know I originally said to retrieve by index (data[0]), but I prefer to retrieve explicitly so that the code is more maintainable.

As a side note, you can eliminate the datatype:'json' declaration in your ajax call by simply setting the header correctly on the PHP side:

header('Content-type: application/json');

Placing that at the top of the document will force the server to recognize the page as json. Far more consistent and explicit than having jQuery look for it.

于 2013-02-21T16:16:27.913 回答