简体   繁体   English

使用 JavaScript 从外部 JSON 文件中获取数据到一个 innerHTML 表中

[英]fetching data from external JSON file into an innerHTML table using JavaScript

I'm trying to fetch data from an external JSON file into the inner HTML but I can't understand what the problem is.我正在尝试将外部 JSON 文件中的数据提取到内部 HTML 中,但我不明白问题是什么。 Data is smoothly displayed through the console but nothing is showing up on the HTML page.数据通过控制台顺利显示,但 HTML 页面上没有显示任何内容。

Everything looks perfect :(一切看起来都很完美:(

Please help me identify and resolve this issue请帮助我确定并解决此问题

    <!DOCTYPE html>
    <html>
    <body>
        <div class="container">
        <table class="table table-stripped">
            <thead>
                <tr>
                    <th>Player ID</th>
                    <th>Player Name</th>
                    <th>Player Country</th>
                </tr>
            </thead>
            <tbody id="data">
            </tbody>
        </table>
        <script>
                fetch("http://localhost/test.json").then (
                    res=>
                    {
                        res.json().then
                        (
                            data=>
                            {
                                console.log(data);
                                if(data.length >0)
                                {
                                    var temp = "";

                                    //Beginning of the For loop

                                    data.forEach((u)=>{
                                        temp +="<tr>";
                                        temp +="<td>"+u.Id+"</td>";
                                        temp +="<td>"+u.Name+"</td>";
                                        temp +="<td>"+u.Country+"</td>"
                                        temp +=  "</tr>";
                                        })
                                    // --- End of the For Loop

                                    document.getElementById("data").innerHTML = temp; //The #tbody ID
                                }
                            }
                        )
                    }
                )
        </script>
    </body>
    </html>

Javascript objects do not have length property. Javascript 对象没有length属性。 That value will be undefined , hence your conditional will never run.该值将是undefined ,因此您的条件将永远不会运行。

Instead you can do:相反,您可以这样做:

if (Object.keys(data).length > 0)

If you want to ensure it doesn't die when there is no data (ie undefined), you can do:如果你想确保它在没有数据(即未定义)时不会死,你可以这样做:

if (typeof(data) === 'object' && Object.keys(data).length > 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM