본문 바로가기
IT/Html + CSS + JS

[Html + JSON ] script 영역에서 테이블 생성하기

by AngieLee 2021. 6. 8.

jsonfile

[
	{
		"title":"언어의 온도",
		"author":"이기주",
		"price":"13,000"
	},
	{
		"title":"방황하는 칼날",
		"author":"히가시노 게이고",
		"price":"22,950"
	},
	{
		"title":"몽실언니",
		"author":"권정생",
		"price":"11,000"
	},
	{
		"title":"하악하악",
		"author":"이외수",
		"price":"13,050"
	},
	{
		"title":"자존감 수업",
		"author":"윤홍균",
		"price":"14,000"
	}

]

 

file 내용 한꺼번에 출력하기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<p id="demo"></p>

<script type="text/javascript">

let xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function () {
	
	if(xhttp.readyState == 4 && xhttp.status == 200) {
		jsonfunc(xhttp.responseText);					 
	}
}
xhttp.open("GET", "book.json", true);
xhttp.send();

function jsonfunc( jsonText ) {

	let json = JSON.parse(jsonText);

	let txt = " ";

	for(i = 0; i < json.length; i++){
		txt += json[i].title + " " + json[i].author + " "
				+ json[i].price + "<br>";
	}
	
	document.getElementById("demo").innerHTML = txt;

}

</script>

</body>
</html>

실행결과

 

 

테이블에 담기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

내가 읽은 책<br><br>
<table border='2' id="bookname">

<tr>
	<th>제목</th><th>저자</th><th>가격</th>
</tr>
</table>

<script type="text/javascript">
let xhttp = new XMLHttpRequest(); // json도 데이터를 읽어오려면 XML을 사용한다.

xhttp.onreadystatechange = function () {
   // 파일을 읽어들이는 것을 성공했을 때
   if(xhttp.readyState == 4 && xhttp.status == 200){
      jsonfunc(this.responseText); //this = xhttp
//      jsonfunc(xhttp.responseText); // 둘다 가능
   }
}
xhttp.open("GET","book.json", true);
xhttp.send();

function jsonfunc( jsonText ) {
	   let arrTitle = new Array();
	   let arrAuthor = new Array();
	   let arrPrice = new Array();
	   
	   let json = JSON.parse(jsonText); // json 파일로 바꾸기
	   
	   for(i=0; i<json.length; i++){ // 값 전체 가져오는법
	      arrTitle[i] = json[i].title;
	      arrAuthor[i] = json[i].author;
	      arrPrice[i] = json[i].price;
	   }
	   
	   let table = document.getElementById('bookname');

	   for(i=0; i<arrTitle.length; i++){
	      let tr = document.createElement("tr");
	      
	      let td1 = document.createElement("td");           
	      td1.appendChild(document.createTextNode(arrTitle[i] + ""));
	      
	      let td2 = document.createElement("td");          
	      td2.appendChild(document.createTextNode(arrAuthor[i] + ""));
	      
	      let td3 = document.createElement("td");          
	      td3.appendChild(document.createTextNode(arrPrice[i]+ ""));
	      
	      tr.appendChild(td1);
	      tr.appendChild(td2);
	      tr.appendChild(td3);
	      
	      table.appendChild(tr);
	   }
	}

</script>

</body>
</html>

실행결과