CLASS/AJAX
#5-4 / Jquery Ajax & 외부 서버 통신(CORS)
hingu
2024. 7. 19. 12:13
⚡ CORS
spring - @CrossOrigin(origins = "*", allowedHeaders = "*") 해당 annotaion 추가
=> origins에 특정 ip 작성시 - 해당 ip에서만 대응하겠다 (* : 전체)
=> allowedHeaders 에 "GET" 작성시 get일 경우만 대응하겠다
(* : 전체 , "application/json" 처럼 type을 작성하는 경우도 있음)
res.addHeader("Access-Control-Allow-Origin","*");
res.addHeader("Access-Control-Allow-Credintials","true");
=> class내에 요걸로 작성으로 대체 가능 (retrun에 경로 넣어줘야함)
json으로 받는다면
@GetMapping(value="/jq/rest_json3.do",produces="application/json") 요런식으로 변경
- ajax3.jsp
<body> <input type="button" value="외부 데이터 로드" id="btn"> </body> <script> $(function(){ $("#btn").click(function(){ $.ajax({ url : "http://172.30.1.5:8080/jq/rest_json3.do", cache : false, type : "GET", //mode : "no-cors", //요건 ecma에서만 가능 (이건 jquery ^^,,) dataType : "HTML", success:function($data){ console.log($data) }, error:function($data){ console.log("서버파일 오류!"); } }); }); }) </script>
- apimain.java (@Controller) - @GetMapping("/jq/rest_json3.do") : 짝꿍이 작성한 파일//CORS @CrossOrigin(origins = "*", allowedHeaders = "*") //res.addHeader 없이 사용 가능은 어노테이션 @GetMapping("/jq/rest_json3.do") public String rest_json3(Model m) { Object data[][] = { {"선풍기",50000}, {"치약",5000} }; JSONArray ja = new JSONArray(); int w = 0; while(w<data.length) { JSONObject jo = new JSONObject(); jo.put("product_name", data[w][0]); jo.put("product_money", data[w][1]); ja.add(jo); w++; } JSONObject jo2 = new JSONObject(); jo2.put("product", ja); m.addAttribute("arr",jo2); System.out.println(jo2); return null; }
- rest_json3.jsp (결과 찍을 파일)<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %> ${arr}
=> 남의 서버에서 요청해도 배열 잘나옴..!
👀 배열 만들어보기 ..^^^..
⚡ 1요렇게 만들기 🔽
Object data[][] = { {"선풍기",50000}, {"치약",5000} }; JSONArray ja = new JSONArray(); int w = 0; while(w<data.length) { JSONObject jo = new JSONObject(); jo.put("product_name", data[w][0]); jo.put("product_money", data[w][1]); ja.add(jo); w++; } JSONObject jo2 = new JSONObject(); jo2.put("product", ja);
잘찍히네여^^...
⚡ 2🔽
/**/
⚡ 3🔽
<!---->