1. 개요
jQuery를 사용하여 Ajax를 구현할 때 JSON 사용 예제이다. jQuery를 사용하면 일반 자바스크립트를 사용하는 것보다 가독성이 좋다. 물론 XMLHttpRequest 객체를 통해 일반 자바스크립트로도 구현 가능하나 status 값 등을 잘 사용해야 하며 브라우저 특성에 따른 처리가 필요하다.
2. JSON 데이터를 내부 var로 설정
[ html 파일 ]
<!doctype html> <html> <head> <title>Info</title> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> </head> <body> <h2>Info</h2> <table id="example" border="2" width="500" height="70" cellpadding="5"> <tr align="center"> <th>No</th> <th>Name</th> <th>Age</th> </tr> </table> <script type="text/javascript"> $(document).ready(function(){ var response = [{ "no":"1", "name":"Kim", "age":"28" }, { "no":"2", "name":"Lee", "age":"35" }]; var tableData = ""; $.each(response, function(index, value){ tableData += '<tr>'; tableData += '<td>'+value.no+'</td>'; tableData += '<td>'+value.name+'</td>'; tableData += '<td>'+value.age+'</td>'; tableData += '</tr>'; }); $("#example").append(tableData); }); </script> </body> </html>
3. JSON 데이터를 별도 파일로 설정
※ 주의사항: 브라우저에서 로컬 파일 호출 방식으로는 안됨. (대부분의 브라우저가 ajax 요청을 지원하지 않음, 보안문제?) 따라서 로컬에서는 톰캣이나 웹 서버를 띄우고 테스트해야 함.
[ info.json 파일 ]
[{ "no":"1", "name":"Kim", "age":"28" }, { "no":"2", "name":"Lee", "age":"35" }]
[ html 파일 ]
<!doctype html> <html> <head> <title>Info</title> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> </head> <body> <h2>Info</h2> <table id="example" border="2" width="500" height="70" cellpadding="5"> <tr align="center"> <th>No</th> <th>Name</th> <th>Age</th> </tr> </table> <script type="text/javascript"> $(document).ready(function(){ $.ajax({ dataType: "json", url: "info.json", mimeType: "application/json", success: function(result){ var tableData = ""; $.each(result, function(index, value) { tableData += '<tr>'; tableData += '<td>'+value.no+'</td>'; tableData += '<td>'+value.name+'</td>'; tableData += '<td>'+value.age+'</td>'; tableData += '</tr>'; }); $("#example").append(tableData); } }); }); </script> </body> </html>