개요
html 파일에서 local의 json 파일을 읽어 웹 페이지에 출력하고자 한다.
내용
Json 파일
[
{
"name" : "Messi",
"birth" : "1987-06-24",
"nation" : "Argentina"
},
{
"name" : "Mbappé",
"birth" : "1998-12-20",
"nation" : "France"
}
]
Html 파일
<meta charset="utf-8">
<head>
<h1>Json Test</h1>
</head>
<body>
<div class="grid" id="grid">
<script type="text/javascript">
let http = new XMLHttpRequest();
function CreateElement(name, birth, nation){
let li = document.createElement('li');
let content = 'Name : ' + name + ' / birth : ' + birth + ' / nation : ' + nation;
let text = document.createTextNode(content);
li.append(text);
return li;
}
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
jsonfunc(this.responseText); //this = http
}
}
// data.json 경로는 html 파일과 동일 폴더에 위치함.
http.open("GET", 'data.json', true);
http.send();
function jsonfunc(jsonText) {
// String -> json으로 변환
let json = JSON.parse(jsonText);
// ul Element 생성
var ul = document.createElement('ul');
for(var i = 0; i < json.length; i++){
const player = json[i];
// li Element 생성
let li = CreateElement(
player.name,
player.birth,
player.nation);
ul.append(li);
}
document.getElementById("grid").append(ul);
}
</script>
</div>
</body>
결과
https://github.com/jaywapp/Tutorials.Web/tree/master/Node.js/230103_2
'Software Develop > Web' 카테고리의 다른 글
[API] 공공데이터 API 사용하기 (0) | 2023.03.08 |
---|---|
[React] github pages를 활용하여 React 프로젝트 배포하기 (0) | 2023.03.08 |
[JavaScript] let과 var 차이 (0) | 2023.01.02 |