【问题标题】:JSON: Cannot read property '0' of undefinedJSON:无法读取未定义的属性“0”
【发布时间】:2015-10-06 18:26:27
【问题描述】:

我正在尝试将 JSON 数据解析为 html 表,但我得到:

“无法读取未定义的属性‘0’”

<?php

$idmatchs = "bGdzkiUVu,bCrAvXQpO,b4I6WYnGB,bMgwck80h";

$exploded = explode(",", $idmatchs);
$count = count($exploded);

?>

<script>
$.get( "obte2.php?id=f_1_0_-3_es_1", function ( data ) {
    var json = eval ("(" + data + ")");

    var matchids = "<?php echo $idmatchs ?> ";
    var ids =  matchids.split(",");

    for (i=0; i < ids.length; i++) {
        $( "#"+ids[i] + " #est" ).html( json.ids[i][0].EST );   
    }

});

</script>


<table class="tg">

 <?php

 for( $i= 0 ; $i < $count ; $i++ ){

    echo '<tr id="'.$exploded[$i].'">';
    echo '<td id="est"></td>';
    echo '</tr>';

  }

 ?>
 </table>

Chrome 突出显示这一行:

$( "#"+ids[i] + " #est" ).html( json.ids[i][0].EST );

事实上,如果我将 ids[i] 替换为任何 id,代码就可以完美运行。

$( "#"+ids[i] + " #est" ).html( json.bGdzkiUVu[0].EST );

JSON 文件是这样的:

{
"bGdzkiUVu": [
    {
        "INI": "1437150600",
        "EST": "PROG",
        "AC": "1",
        "LCL": "Amberg",
        "AX": "0",
        "LIN": "AMB",
        "AE": "Amberg",
        "WU": "amberg",
        "OA": "team",
        "WN": "MEM",
        "VST": "Memmingen",
        "WV": "memmingen",
        "OB": "team",
        "AN": "y"
    }
],
"bCrAvXQpO": [
    {
        "INI": "1437150600",
        "EST": "PROG",
        "AC": "1",
        "LCL": "SpVgg Bayreuth",
        "AX": "0",
        "WN": "SCH",
        "VST": "Schalding",
        "WV": "schalding",
        "OB": "team",
        "LIN": "SPV",
        "AE": "SpVgg Bayreuth",
        "WU": "spvgg-bayreuth",
        "OA": "team",
        "AN": "y"
    }
],
"b4I6WYnGB": [
    {
        "INI": "1437152400",
        "EST": "PROG",
        "AC": "1",
        "LCL": "1860 Munich II",
        "AX": "0",
        "LIN": "186",
        "AE": "1860 Munich II",
        "WU": "1860-munich",
        "OA": "team",
        "WN": "BUR",
        "VST": "Burghausen",
        "WV": "burghausen",
        "OB": "team",
        "AN": "y"
    }
],
"bMgwck80h": [
    {
        "INI": "1437152400",
        "EST": "PROG",
        "AC": "1",
        "LCL": "Buchbach",
        "AX": "0",
        "LIN": "BUC",
        "AE": "Buchbach",
        "WU": "buchbach",
        "OA": "team",
        "WN": "RAI",
        "VST": "Rain/Lech",
        "WV": "rain-lech",
        "OB": "team",
        "AN": "y"
    }
]
}

【问题讨论】:

    标签: javascript php json html-table


    【解决方案1】:

    您要求 JS 查找 ids[i],当您实际查找 ids.bGdzkiUVu 时,它的计算结果实际上是 ids[0] 或 ids[1]。而不是使用索引,您需要通过键来查找它们。

    例如:

    Object.keys(ids).forEach(function (key) {
        // do something with ids[key]
    });
    

    【讨论】:

    • 我把你的代码放在了 for 循环中,但我仍然无法让它工作。为什么“ids[i]”在 JQuery 选择器中有效,但在我尝试设置为 html 时无效?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多