首页 > 解决方案 > 如何访问包含对象的 JSON 数组中的值

问题描述

我想遍历我的 JSON 结果并获取每个对象的值来对它们求和。这是我的 JSON 结果:

[{"Duree":"01:00:00"},{"Duree":"00:30:00"},{"Duree":"01:00:00"}]

然后我在我的 Ajax 方法中执行此操作:

var xhr1 = getXhr();
    xhr1.onreadystatechange = function(){
        if(xhr1.readyState == 4 && xhr1.status == 200){
            Selection = xhr.responseText;
            for(var i = 0; i < Selection.length; i++) {
                if (i != 0) {
                    start = tot;
                }
                else if (i === 0){
                    start = Selection[0];
                }
                if ((i + 1) >= Selection.length) {
                    end = Selection[i + 1];
                    tot = addTimes(start, end);
                }
            }
            alert(tot);
        }
    };

我的 php 代码生成我的 json 输入:

foreach($rep as $Intervention) {
    if ($Intervention['Vacation'] == $idVacation) {
        $Query = 'SELECT Duree FROM fairegammeoperatoire WHERE IDIntervention=:id';
        $rep = $bdd->prepare($Query);
        $custom = $Intervention['IDIntervention'];
        $rep->bindParam(':id',$custom);
        $rep->execute();
        $Duree = $rep->fetch(PDO::FETCH_ASSOC);
        $tot = $Duree;
        array_push($total, $tot);
    }
}
echo json_encode($total);

编辑:问题是 JSON.parse 中使用的变量 xhr 的名称不是好的名称。必须是 xhr1 而不是 xhr。全部=D

标签: javascriptphpjsonajaxtime

解决方案


您是否尝试将其解析为 json 对象:它必须被解析,因为响应将被读取为字符串。

var xhr1 = getXhr();
    xhr1.onreadystatechange = function(){
        if(xhr1.readyState == 4 && xhr1.status == 200){
            Selection = JSON.parse(xhr1.responseText);
            for(var i = 0; i < Selection.length; i++) {
                if (i != 0) {
                    start = tot;
                }
                else if (i === 0){
                    start = Selection[0].Duree;
                }
                if ((i + 1) >= Selection.length) {
                    end = Selection[i + 1].Duree;
                    tot = addTimes(start, end);
                }
            }
            alert(tot);
        }
    };

您的 json 必须类似于

<?php 
$dataArray = array(array("Duree"=>"01:00:00"),array("Duree"=>"02:00:00"),array("Duree"=>"03:00:00"),array("Duree"=>"04:00:00"));
echo json_encode($dataArray);
?>

推荐阅读