jquery를 이용한 jsonp 처리 방법

프로그래밍|2013. 7. 11. 11:28

test.co.kr 이라는 사이트에서 dev.co.kr 이라는 사이트에 있는 정보를 Ajax 기술을 이용하여 요청을 보낼 때 cross domain policy에 의해 브라우저가 요청을 막는다.

즉, 도메인이 다르면 요청을 보낼 수 없다.


위와 같은 상황을 우회하여 해결할 수 있는 방법은 jquery에서 jsonp를 이용하는 것이다.

한 가지 주의해야 할점은 jsonp는 HTTP GET 방식만 지원한다.


jsp 파일

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

<script type="text/javascript">

 

         $(document).ready(function() {

         });

 

         function getJsonTest1() {

                  $.getJSON("http://jsonp.localhost:8081/jsonpTest?id=user&callback=?",

                           function(data) {

                                   alert(data.id + ", " + data.result);

                           }

                  );

         }

 

         function postJsonTest2() {

                  $.ajax({

                           type : "GET",

                           url : "http://jsonp.localhost:8081/jsonpTest",

                           data : "id=kyu",

                           dataType : "jsonp",

                           success : function(json) {

                                   alert(json.id + ", " + json.result);

                           },

                           error : function(e) {

                                   alert("error");

                           }

                  });

         }

</script>

 

 

<a href="javascript:postJsonTest2();">

         test

</a>


java 파일

@RequestMapping(value = "/jsonpTest", method = RequestMethod.GET)

         @ResponseBody

         public String jsonpTest(@RequestParam String id, @RequestParam String callback) {

                  Map<String, String> paramMap = new HashMap<String, String>();

                  paramMap.put("id", id);

                  paramMap.put("result", "success");

 

                  String result = null;

                  ObjectMapper mapper = new ObjectMapper();

                  try {

                           result = mapper.writeValueAsString(paramMap);

                  } catch (JsonGenerationException e) {

                           e.printStackTrace();

                  } catch (JsonMappingException e) {

                           e.printStackTrace();

                  } catch (IOException e) {

                           e.printStackTrace();

                  }

 

                  System.out.println(result);

                  return callback + "(" + result + ")";

         }


크로스 도메인 요청 테스트를 위해 hosts 파일에 다음을 등록한다.

127.0.0.1 jsonp.localhost


Ajax 요청에 대한 HTTP request 및 response를 확인해 보면 다음과 같다.


HTTP request


HTTP response body

jQuery183023385174595750868_1373508690112({"id":"kyu","result":"success"})



크로스 도메인 제약을 피하기 위해 jsonp를 이용하여 우회를 하게 되는데 동작 원리가 잘 이해가 되지 않는다.

역시 자바스크립트는 어렵다.


조만간 자바스크립트 스터디 모임에 참여해서 빡시게 공부 좀 해야 겠다.

댓글()