본문 바로가기
JavaScript/Ajax

Ajax) text/csv 처리

by 박채니 2022. 7. 12.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


CSV

 

text.jsp

<h2>csv</h2>
<input type="button" value="Celeb 불러오기" id="btn-celeb" />

<script>
document.querySelector("#btn-celeb").addEventListener('click', (e) => {
    $.ajax({
        url : '<%= request.getContextPath() %>/celeb/csv',
        method : 'GET', // 기본값이 GET이기 때문에 생략 가능
        success(response) {
            console.log(response);
        },
        error(jqxhr, statusText, err) {
            console.log(jqxhr, statusText, err);
        }
    });
});
</script>

 

CelebCsvServlet

@WebServlet("/celeb/csv")
public class CelebCsvServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. 사용자입력값
		
		// 2. 업무로직
		CelebManager manager = CelebManager.getInstance();
		List<Celeb> celebList = manager.getCelebList();
		
		// 3. 응답처리
		response.setContentType("text/csv; charset=utf-8");
		PrintWriter out = response.getWriter();
		for(Celeb celeb : celebList) {
			out.println(celeb);
		}
	}
}

csv 형태로 데이터를 잘 받아온 것을 확인할 수 있으며, 이를 이용하여 HTML에 랜더링 해주겠습니다.

 

text.jsp

<h2>csv</h2>
<input type="button" value="Celeb 불러오기" id="btn-celeb" />

<table id="tbl-celeb">
    <thead>
        <tr>
            <th>No</th>
            <th>이름</th>
            <th>프로필</th>
            <th>구분</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>

<script>
document.querySelector("#btn-celeb").addEventListener('click', (e) => {
    $.ajax({
        url : '<%= request.getContextPath() %>/celeb/csv',
        method : 'GET', // 기본값이 GET이기 때문에 생략 가능
        success(response) {
            console.log(response);

            const tbody = document.querySelector("#tbl-celeb tbody");
            tbody.innerHTML = '';
            const celebs = response.split("\r\n");
            celebs.forEach((celeb) => {
                if(celeb === '') return;
                const [no, name, profile, type] = celeb.split(",");

                const tr = document.createElement("tr");
                const tdNo = document.createElement("td");
                tdNo.append(no);

                const tdName = document.createElement("td");
                tdName.append(name);

                const tdProfile = document.createElement("td");
                const img = document.createElement("img");
                img.src = `<%= request.getContextPath() %>/images/\${profile}`;
                tdProfile.append(img);

                const tdType = document.createElement("td");
                const select = document.createElement("select");
                const option1 = document.createElement("option");
                option1.value = "ACTOR";
                option1.append("연기자");
                const option2 = document.createElement("option");
                option2.value = "MUSICIAN";
                option2.append("음악가");
                const option3 = document.createElement("option");
                option3.value = "MODEL";
                option3.append("모델");
                const option4 = document.createElement("option");
                option4.value = "ENTERTAINER";
                option4.append("예능인");
                const option5 = document.createElement("option");
                option5.value = "COMEDIAN";
                option5.append("개그맨");
                select.append(option1, option2, option3, option4, option5);
                tdType.append(select);
                select.value = type;

                tr.append(tdNo, tdName, tdProfile, tdType);
                tbody.append(tr);
            });
        },
        error(jqxhr, statusText, err) {
            console.log(jqxhr, statusText, err);
        }
    });
});
</script>

받은 CSV 데이터를 이용해 DOM으로 제어하여 나타내보았습니다.

'JavaScript > Ajax' 카테고리의 다른 글

Ajax) 검색어 자동완성 기능 (Autocomplete)  (0) 2022.07.12
Ajax) text/html 처리  (0) 2022.07.12
Ajax) text/plain 처리  (0) 2022.07.08
Ajax) 동기와 비동기 차이, Javascript로 비동기처리  (0) 2022.07.08
Ajax) 정리  (0) 2022.07.08