CLASS/AJAX
#5-6 / ECMA - Ajax 데이터 로드
hingu
2024. 7. 19. 16:17
- ajax5.jsp
<body> <input type="button" value="ecma_ajax" id="btn"> </body> <script type="module"> import {data} from "./ajax5.js"; document.querySelector("#btn").addEventListener("click",function(){ data.ajax(); }); </script>
- ajax5.js ( ajax5.jsp 와 연결 )export let data = { keycode : "a1234", //가상 변수 선언 - 인증키는 요런식으로 쓰면 댐 ajax : function(){ //console.log(this.keycode); //해당 가상변수이며, 출력시 this를 활용함- a1234 출력 //Get일 경우 별도의 method 사용하지 않아도 됨 fetch("http://172.30.1.5:8080/jq/rest_ajax5.do",{ method:"GET", cache:"no-cache", //mode:"no-cors", //이거 쓰면 안됨 - get은 무조건 backend가 처리! (위에 두줄도 안써도 되는듯) }) .then(function(node){ //Back-end에서 받는 데이터 return node.json(); //json이 아니면 이게 또 에러남 (걍 텍스트면 text()로 작성) }).then(function(alldata){ //데이터를 출력 // var db = JSON.parse(alldata); console.log(alldata); }).catch(function(error){ //에러 발생 console.log(error) console.log("서버접속 오류!!") }); } }
⭐ ⭐ ⭐ GET을 사용시 fetch에서 절대 mode를 사용하지 않음!! (Backend 에서 crossorigin으로 처리!!)
- @controller//ECMA Ajax Mapping @CrossOrigin(origins="*", allowedHeaders = "*") @GetMapping("/jq/rest_ajax5.do") public String rest_ajax5(HttpServletResponse res) throws Exception { res.setContentType("text/html;charset=utf-8"); this.pw = res.getWriter(); try { Connection con = dbInfo.getConnection(); String sql = "select uidx,uid,uname,ujoin from user order by uidx desc"; this.ps = con.prepareStatement(sql); this.rs = this.ps.executeQuery(); JSONArray alldata = new JSONArray(); while(this.rs.next()) { JSONArray ja = new JSONArray(); ja.add(this.rs.getString(1)); ja.add(this.rs.getString(2)); ja.add(this.rs.getString(3)); ja.add(this.rs.getString(4)); alldata.add(ja); } con.close(); this.pw.print(alldata); }catch(Exception e) { e.getStackTrace(); }finally { this.rs.close(); this.ps.close(); } return null; }
다른 서버에서 요청할시 back-end에서 crossorigin 필수!
=> console에 json 찍히면 👍
🔽
처음부터 back-end에서 json으로 보내야 한다면?
@GetMapping(value="/jq/rest_ajax5.do",produces="application/json")
요렇게 보내서
export let data = {
ajax : function(){
fetch("./rest_ajax5.do")
.then(function(node){
return node.text();
}).then(function(alldata){
console.log( JSON.parse(alldata));
}).catch(function(error){
console.log("서버접속 오류!!")
});
}
}
요렇게 받기
=> backend에서 application/json으로 모드를 바꿨기때문에
front에서 text로 받아서 json.parse()로 받기 가능
( application/html일경우 json.parse() 사용 불가능 )