본문 바로가기
IT Study/JQuery

JQuery - Ajax/json 데이터 활용

by hhyyyjun 2023. 1. 1.

| Ajax(Asynchronous JavaScript and XML)

JQuery에서 비동기처리를 담당하는 메서드

Json 데이터와 함께 활용

특징

페이지 새로고침 없이 서버에 요청

서버로부터 데이터를 받고 작업을 수행

Ajax의 장점

1. 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있다.

2. 웹 페이지가 로드된 후에 서버로 데이터 요청을 보낼 수 있다.

3. 웹 페이지가 로드된 후에 서버로부터 데이터를 받을 수 있다.

4. 백그라운드 영역에서 서버로 데이터를 보낼 수 있다.

Ajax 메서드 기본 형태

$.ajax({
	type: "GET",
	url: "data.json",
	dataType: "json",
	success: function (data) { //성공할 시 사용할 함수

	}
	$.each(data, function (index, obj){ //데이터가 들어갈 함수

	}
	$("요소명").append(객체명); //추가할 태그
	},
	error: function (error) { //에러 발생 시 확인
	console.log(error.status);
	console.log(error.errorText);
	},
});

Practice. Json 데이터를 활용하여 테이블 추가하기

Json data

[
  { "name": "홍길동", "score1": 95, "score2": 90, "score3": 80, "score4": 85 },
  { "name": "홍길순", "score1": 80, "score2": 75, "score3": 60, "score4": 75 }
]

 

HTML

<table>
      <caption>
        학생들의 시험점수
      </caption>
      <thead>
        <tr>
          <th>이름</th>
          <th>시험1</th>
          <th>시험2</th>
          <th>시험3</th>
          <th>시험4</th>
        </tr>
      </thead>
      <tbody></tbody>  //이 안에 들어갈 예정
    </table>

 

JS

<script type="text/javascript">
      //jquery 라이브러리에서
      //비동기 처리를 담당(실시간으로 데이터를 로드하는)하는 메서드

      //ajax 메서드의 기본형태
      $.ajax({
        type: "GET", //URL에 보여질 형태
        url: "data.json",
        dataType: "json",
        success: function (data) {
          // data는 data.json의 전체데이터를 의미
          console.log("성공!");
          let elem = ""; //elem의 default 값

          $.each(data, function (index, obj) {
            //obj는 json에 저장된 개별 객체를 의미
            elem += "<tr>";
            elem += "<td>" + obj.name + "</td>";
            elem += "<td>" + obj.score1 + "</td>";
            elem += "<td>" + obj.score2 + "</td>";
            elem += "<td>" + obj.score3 + "</td>";
            elem += "<td>" + obj.score4 + "</td>";
            elem += "</tr>";
          });

          $("table tbody").append(elem);
        },
        error: function (error) {
          console.log(error.status);
          console.log(error.errorText);
        },
      });
    </script>

 

append 메서드를 사용하여 tbody 하위에 데이터가 생성되도록 하였다.


Practice2. Json 데이터를 활용하여 이미지/경로 추가하기

Json data

[
  {"name": "일러스트","imgName": "france1.jpg","link": "https://www.naver.com"},
  {"name": "리뷰","imgName": "france2.jpg","link": "https://www.youtube.com"},
  {"name": "사진","imgName": "france3.jpg","link": "https://comic.naver.com/index"}
]

 

각 데이터 삽입, 연결할 url 정보 삽입

HTML

<div id="wrapper">
      <h1>ajax() 메서드 실습</h1>
      <div id="imgwrapper">
        <div id="h2wrapper"></div>   //하위요소에 제목이 들어감
        <div id="img"></div>  //하위요소에 사진이 들어감
      </div>
    </div>

 

JS

<script type="text/javascript">
      $.ajax({
        type: "GET",
        url: "imgdata.json",
        dataType: "json",
        success: function (data) {
          console.log("성공!");
          let elem = "";
          let elem2 = "";

          $.each(data, function (index, obj) {
            elem2 += "<h2 id='h2box'>" + obj.name + "</h2>";
            elem +=
              "<a href='" +
              obj.link +
              "'><img src='./images/" +
              obj.imgName +
              "' alt='" +
              obj.name +
              "'></a>";
          });
          $("#imgwrapper #h2wrapper").append(elem2);
          $("#imgwrapper #img").append(elem);
        },
        error: function (error) {
          console.log(error.status);
          console.log(error.errorText);
        },
      });
    </script>

각 이미지 클릭 시 연결된 url로 이동할 수 있다.

댓글