Web

[JavaScript] JSON 데이터 table 형태로 표현하기

yerinpark 2023. 12. 28. 14:55

DB에서 여러 건을 가져와서 html에 테이블 형식으로 출력하고자 한다.

 

DeptController.java

우선 Controller에서 ObjectMapper를 사용해서 객체 타입의 데이터를 JSON 형태로 바꿔준다.

@WebServlet("/dept")
public class DeptController extends HttpServlet {
	DeptDAO dao = new DeptDAO();
      
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString(dao.selectAll());

			request.setAttribute("all", json);
			request.getRequestDispatcher("deptAllRes.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

deptAllRes.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

${requestScope.all}

 

 

deptAjax.html

dept_data 변수에 String 문자열을 더해서 table 태그의 html 코드를 작성한다.

thead 작성 시 백틱(`)을 사용해서 가독성을 높였다.

 

파싱한 JSON 데이터를 foreach를 사용하여 dept_data에 넣는다.document.getElementById("dept_table").innerHTML = dept_data;문서에서 id가 dept_table인 table 태그 안에 dept_data를 넣어준다.

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>deptAjax.html</title>
</head>

<body>
	<button id="btn">모든 부서 정보 보기</button>
	<br>
	<div id="deptView">
		<table border="1" id="dept_table">
		</table>
	</div>

	<script>
		// step02 - 비동기 통신
		document.querySelector("#btn").addEventListener("click", function () {
			var xhttp = new XMLHttpRequest();

			xhttp.onreadystatechange = function () {
				if (this.readyState == 4 && this.status == 200) {
					let data = JSON.parse(this.responseText);

					let dept_data = `
					<thead>
						<tr>
							<th>deptno</th>
							<th>dname</th>
							<th>loc</th>
						</tr>
					</thead>`;

					data.forEach((number, index) => {
						dept_data += "<tr>";
						dept_data += "<td>" + data[index].deptno + "</td>"
						dept_data += "<td>" + data[index].dname + "</td>"
						dept_data += "<td>" + data[index].loc + "</td>"
						dept_data += "</tr>";
					});

					document.getElementById("dept_table").innerHTML = dept_data;
				}
			};
			xhttp.open("GET", "dept", true);
			xhttp.send();
		});

	</script>
</body>

</html>

 

 

 

 

 

'Web' 카테고리의 다른 글

[JavaScript] String을 배열로 파싱하기  (0) 2023.09.15