웹개발 교육/Ajax
[45일] Ajax (2) - json 데이터 받아오기 1
ewok
2022. 9. 29. 11:38
json 데이터를 받아오기 위해 우선 json 파일을 준비하자
sungjuk.json
[
{"name":"John", "id":"itwill", "kor":70, "eng":80, "mat":90}
]
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>04_json데이터가져오기.html</title>
<script src="jquery-3.6.1.min.js"></script>
</head>
<body>
<button>* JSON 데이터 받아오기 *</button>
<div id="panel"></div>
<script>
$("button").click(function(){
$.ajax("sungjuk.json", {
dataType:"json"
,error:function(error){
alert("ERROR!!" + error);
}//error end
,success:function(result){
alert("SUCCESS!!");
alert(result); //서버가 응답해준 객체 형태의 데이터
}//success end
});//ajax() end
});//click end
</script>
</body>
</html>
서버로부터 함수가 응답을 받는다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>04_json데이터가져오기.html</title>
<script src="jquery-3.6.1.min.js"></script>
</head>
<body>
<button>* JSON 데이터 받아오기 *</button>
<div id="panel"></div>
<script>
$("button").click(function(){
$.ajax("sungjuk.json", {
dataType:"json"
,error:function(error){
alert("ERROR!!" + error);
}//error end
,success:function(result){
// alert("SUCCESS!!");
// alert(result); //서버가 응답해준 객체 형태의 데이터
// alert(result.length);
let size = result.length;
let str = "<table border='1'>";
for(i=0; i<size; i++){
str += "<tr>";
str += " <td>" + result[i].name + "</td>";
str += " <td>" + result[i].id + "</td>";
str += " <td>" + result[i].kor + "</td>";
str += " <td>" + result[i].eng + "</td>";
str += " <td>" + result[i].mat + "</td>";
str += "</tr>";
}//for end
str += "</table>";
$("#panel").html(str);
}//success end
});//ajax() end
});//click end
</script>
</body>
</html>
댓글 더보기는 더보기 버튼을 클릭하면 아래로 댓글들이 계속 쌓인다. 이렇게 한번 해보자
$("#panel").html(str);
html 함수 대신 append 함수를 사용하면 된다.
$("#panel").append(str);