如何在html代码中使用json文件

how to use json file in html code

本文关键字:json 文件 代码 html      更新时间:2023-09-26

我有json文件mydata.json,这个文件中有一些json编码的数据。

我想在文件index.html中获得这些数据,并用JavaScript处理这些数据。但是一个不知道如何在.html文件中连接.json文件的人?

请告诉我。这是我的json文件:

{
    "items": [
        {
            "movieID": "65086",
            "title": "The Woman in Black",
            "poster": "/kArMj2qsOnpxBCpSa3RQ0XemUiX.jpg"
        },
        {
            "movieID": "76726",
            "title": "Chronicle",
            "poster": "/853mMoSc5d6CH8uAV9Yq0iHfjor.jpg"
        }
    ]
} 

考虑到我正在从服务器获取json文件,如何在我的html中使用该文件,以便在html页面中的表中显示数据。我使用JavaScript来解析json文件。我是这个领域的新手。请帮忙。

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
    $(function() {

   var people = [];
   $.getJSON('people.json', function(data) {
       $.each(data.person, function(i, f) {
          var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
           "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
           $(tblRow).appendTo("#userdata tbody");
     });
   });
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
   <table id= "userdata" border="2">
  <thead>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email Address</th>
            <th>City</th>
        </thead>
      <tbody>
       </tbody>
   </table>
</div>
</div>
</body>
</html>

我的JSON文件:

{
   "person": [
       {
           "firstName": "Clark",
           "lastName": "Kent",
           "job": "Reporter",
           "roll": 20
       },
       {
           "firstName": "Bruce",
           "lastName": "Wayne",
           "job": "Playboy",
           "roll": 30
       },
       {
           "firstName": "Peter",
           "lastName": "Parker",
           "job": "Photographer",
           "roll": 40
       }
   ]
}

经过一天的工作,我成功地将JSON文件集成到了HTML表中!!!

使用jQuery的$.getJSON

$.getJSON('mydata.json', function(data) {
    //do stuff with your data here
});

您可以很容易地做到这一点,而无需像下面这样使用Jquery或AJAX。在这里,我使用了fetch API(内置)。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
</head>
<body>
<div id="myData"></div>
<script type="text/javascript">
    fetch('data.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            appendData(data);
        })
        .catch(function (err) {
            console.log('error: ' + err);
        });
    function appendData(data) {
        let mainContainer = document.getElementById("myData");
        for (let i = 0; i < data.length; i++) {
            let div = document.createElement("div");
            div.innerHTML = 'Name: ' + data[i].firstName + ' ' + data[i].lastName;
            mainContainer.appendChild(div);
        }
    }
</script>
</body>
</html>

data.json

[
  {
    "id": "1",
    "firstName": "John",
    "lastName": "Doe"
  },
  {
    "id": "2",
    "firstName": "Mary",
    "lastName": "Peterson"
  },
  {
    "id": "3",
    "firstName": "George",
    "lastName": "Hansen"
  }
]

您可以使用JavaScript,比如只需给出json文件的正确路径。。。

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);
                var div = document.getElementById('data');
                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">
        </div>
    </body>
</html>

只需获取数据并将其附加到div.…最初在alert中打印长度。

这是我的Json文件:abc.Json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

以下是如何在纯JavaScript中实现这一点。

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Sample Test Page</title>
    </head>
    <body>
        <h2>Movie List</h2>
        <table id = "tb1" border = "1">
            <tr>
                <th>movieID</th>
                <th>title</th>
                <th>poster</th>
            </tr>
        </table>
        <script>
            fetch("mydata.json")
                .then(response => response.json())
                .then(data => {
                    for (var i = 0; i<data.items.length; i++){
                        let vmovieID = data.items[i].movieID;
                        let vtitle = data.items[i].title;
                        let vposter = data.items[i].poster;
                            document.querySelector("#tb1").innerHTML += `
                                <tr>
                                    <td>${vmovieID}</td>
                                    <td>${vtitle}</td>
                                    <td>${vposter}</td>
                                </tr>`;
                    }
                })
        </script>
    </body>
</html>

mydata.json

{
    "items": [
        {
            "movieID": "65086",
            "title": "The Woman in Black",
            "poster": "/kArMj2qsOnpxBCpSa3RQ0XemUiX.jpg"
        },
        {
            "movieID": "76726",
            "title": "Chronicle",
            "poster": "/853mMoSc5d6CH8uAV9Yq0iHfjor.jpg"
        }
    ]
}