简体   繁体   English

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

[英]how to use json file in html code

I have json file mydata.json , and in this file is some json-encoded data.我有 json 文件mydata.json ,在这个文件中有一些 json 编码的数据。

I want obtain this data in file index.html and process this data in JavaScript.我想在文件index.html中获取这些数据并在 JavaScript 中处理这些数据。 But a don't know how to connect.json file in .html file?但是不知道如何在 .html 文件中连接.json 文件?

Tell me please.请告诉我。 Here is my json file:这是我的json文件:

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

Thinking that I am getting json file from server, how to use that file in my html, so that I can display the data in tables in html page.认为我正在从服务器获取 json 文件,如何在我的 html 中使用该文件,以便我可以在 html 页面的表格中显示数据。 I am using JavaScript to parse the json file.我正在使用 JavaScript 来解析 json 文件。 I am new to this field.我是这个领域的新手。 Help out please.请帮忙。

<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>

My JSON file:我的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
       }
   ]
}

I succeeded in integrating a JSON file to HTML table after working a day on it!!!经过一天的工作,我成功地将JSON文件集成到HTML表中!!!

use jQuery's $.getJSON使用 jQuery 的$.getJSON

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

You can use JavaScript like... Just give the proper path of your json file...您可以使用 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>

Simply getting the data and appending it to a div... Initially printing the length in alert.只需获取数据并将其附加到 div... 最初在警报中打印长度。

Here is my Json file: abc.json这是我的 Json 文件:abc.json

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

You can easily do this without using Jquery or AJAX like below.您可以轻松地做到这一点,而无需像下面那样使用 Jquery 或 AJAX。 Here, I used fetch API (Built-in).在这里,我使用了 fetch API(内置)。

index.html索引.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数据.json

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

Here's how to do it in plain JavaScript.以下是使用纯 JavaScript 的方法。

index.html索引.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我的数据.json

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

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

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