javascript - 如何访问包含对象的 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
解决方案
您是否尝试将其解析为 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);
?>
推荐阅读
- python - 使用“导入模块名称”时 - 变量值和函数(如果有)存储在哪里?
- api - 是否有任何替代 Newsapi 的 react-native
- scrapy - 蜘蛛运行良好,但没有刮掉一些结果
- apache-spark - Spark 是否适合在作业中处理来自 sql db 的数据?如何避免在作业中处理相同的数据?
- android - 如何在 Android 中将视频播放器视图拖到画中画模式?
- python - 正则表达式搜索字符串中带有双引号的单词
- python - Python 调用 PyFIles
- python-3.x - 验证用户帐户后刷新令牌为空
- c# - JetBrains Rider 中的自定义空断言
- powershell - 如何从类方法访问全局变量