본문 바로가기
Web/jQuery

$.getJSON 으로 JSON DATA 읽어오기

by 나비와꽃기린 2016. 11. 4.
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.



jQuery  에서는 getJSON()함수를 통하여 json파일을 읽어올 수 있다.

HTTP GET 방식 요청을 통해 서버로부터 받은 JSON 데이터를 로드하는 것이며 JSON DATA를 읽어오는 ajax라고 생각하면 쉽다.


jQuery.getJSON( url [, data ] [, success ] )


형식으로 사용한다.

URL은 정보를 요청할 URL 혹은 읽어올 파일 위치정보를 입력하면 된다.

DATA는 서버로 보낼 DATA

SUCCESS는 요청이 성공하면 실행될 콜백함수를 뜻한다.



간단한 예제를 보자.



personInfo.json과 jsontTest.jsp 파일을 준비하고 다음과 같이 작성한다.


<<personInfo.json>>


[
	{
	     "firstName": "John",
	     "lastName": "Smith",
	     "age": 25,
	     "address":
	     {
	         "streetAddress": "21 2nd Street",
	         "city": "New York",
	         "state": "NY",
	         "postalCode": "10021"
	     },
	     "phoneNumber":
	     [
	         {
	           "type": "home",
	           "number": "212 555-1234"
	         },
	         {
	           "type": "fax",
	           "number": "646 555-4567"
	         }
	     ]
	 }
 ]



<<jsontTest.jsp>>


<script>
	$(document).ready(function() {
		
	    $.getJSON('/sts/resources/jsonData/personInfo.json', function(data) {
	     
	      var html = [];
	      
	      $.each(data, function(i, item) {
	    	  html.push('<div >');
	    	  html.push('<h3 >' + item.firstName + '</h3>');
	    	  html.push('<div >' + item.lastName + '</div>');
	    	  html.push('<div >' + item.age + '</div>');
	    	  html.push('<div >' + item.address.streetAddress + '</div>');
	    	  html.push('<div >' + item.phoneNumber[0].type + '</div>');
	    	  html.push('</div>');
	    	  html.push('</div>');
	    	  
	    	  //html.push('<li id="' + key + '">' + val + '</li>');
	      });
	      
	      console.log(html);
	      
	      $('#target').html(html.join(''));
	      
	    });
	});
    </script>

</head>
<body>

<div id="target" />

</body>


<<결과>>