down00112 2018-08-13 07:04
浏览 117

如何访问包含对象的JSON数组中的值

I want to loop through my JSON result and get each object's value to sum them. Here is my JSON result :

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

Then i do this in my Ajax method :

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);
        }
    };

My php code which generate my json input :

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);

EDIT : Problem was the name of variable xhr used in JSON.parse that wasn't the good one. Has to be xhr1 and not xhr. TY ALL =D

  • 写回答

1条回答 默认 最新

  • duandai6373 2018-08-13 07:12
    关注

    Have you tried to parse it as json object: It has to be parsed, since the response will be read as string.

    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);
            }
        };
    

    Your json must be something like

    <?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);
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置