source

html 코드에서 json 파일을 사용하는 방법

itover 2023. 3. 8. 21:06
반응형

html 코드에서 json 파일을 사용하는 방법

json 파일이 있습니다.mydata.json이 파일에는 몇 가지 json-syslog 데이터가 포함되어 있습니다.

나는 이 데이터를 파일로 얻고 싶다.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로 사용하는 방법.json 파일을 해석하기 위해 JavaScript를 사용하고 있습니다.저는 이 분야에 익숙하지 않습니다.도와주세요.

<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의 $.getJ 사용아들

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

아래와 같이 Jquery나 AJAX를 사용하지 않고 쉽게 할 수 있습니다.여기서는 fetch API(Built-in)를 사용했습니다.

index.displaces를 표시합니다.

<!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에 추가하는 것만으로...처음에 경고로 길이를 인쇄합니다.

제 Json 파일입니다: abc.json

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

플레인 JavaScript로 하는 방법은 다음과 같습니다.

index.displaces를 표시합니다.

<!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"
        }
    ]
}

언급URL : https://stackoverflow.com/questions/12070631/how-to-use-json-file-in-html-code

반응형