我想遍历我的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);
}
};
生成我的json输入的我的php代码:
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。 TY ALL = D
答案 0 :(得分:0)
您是否尝试过将其解析为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);
?>