AJAX 예제

서현서현·2022년 8월 18일
0

Spring

목록 보기
23/31

간단한 해설

$.ajax({
  type : `http method type`,
  url : `url`,
  data : `서버에 전송할 데이터`,
  contentType : "전송할 데이터 타입",
  //기본 값 : "application / x-www-form-urlencoded; charset = UTF-8"  
  dataType : '서버로 부터 수신할 데이터 타입',
  //아무것도 지정하지 않으면 jQuery는 응답의 MIME 유형을 기반으로 해석을 시도
  error : `에러 발생시 수행할 함수`,
  success : `성공시 수행할 함수`
});

버튼클릭시 댓글등록

$("#replyAddBtn").on("click",function(){
	
	var replyer = $("#newReplyWriter").val();
	var replytext = $("#newReplyText").val();
	
	$.ajax({
		type : 'post',
		url : '/replies',
		headers : {
			"Content-Type" : "application/json",
			"X-HTTP-Method-Override" : "POST"
		},
		dataType : 'text',
		data : JSON.stringify({
			bno : bno,
			replyer : replyer,
			replytext : replytext
		}),
		success : function(result){
			if(result=='success') {
				alert('등록 되었습니다.');
			}
		}
	});
});

POST로 데이터 보내보좍

$.ajax({
  type : 'post',
  url : '${cPath}/reserve/saveReserve',
  contentType: 'application/json',
  data : resvInfos,
  success : function(data){
    if(data == 'success'){
      // controller로 이동
      alert('예약 저장 완료!')
    }
  },
  error : function(data){
    alert("예약이 저장되지 못했습니다!");
  }
});

JSP <-> CONTROLLER

// JSP -> COntroller -> JSP로 데이터 전달하는거 작성할때 주의

$.ajax({
  type : 'post',
  url : '${cPath}/reserve/info/resvSeatInfo',
  contentType: 'application/json',
  data : JSON.stringify(datas),
  dataType : 'json',
  success : function(data){
    block(data);
  },
  error : function(data){
    alert('실패!');
  }
});

JSON으로 보낼거면 JSON.stringify 꼭 하기 안해놓고 승질내지 않기 ㅋㅋ

@ResponseBody
@PostMapping("/info/resvSeatInfo")
public List<String> getResvSitId(@RequestBody ResvInfoVO vo) {
  List<String> resvSitList = new ArrayList<String>();
  try {
    resvSitList = service.reserveSitList(vo);

  } catch (Exception e) {
    e.printStackTrace();
  }

  return resvSitList;
}

컨트롤러에서 JSON 받아서 서비스 실행하고, 반환받은 값을 JSP로 다시 보내줄거임

 dataType : 'json' <= 돌려받는거 json인거 명시 안하고 승질부리지 않기
 'text'로 설정해두고 <List><item>ET0</item></List> 이렇게 나오는거 황당해하지말기~^^
 받은 데이터는 함수 block()으로 실행!
   
function block(data){
  // data에 들어온 좌석을 블락해준다
  console.log(data);
  for (var i in data) {
    let blockSitId = data[i];
    $("#"+blockSitId).attr("disabled", true);  									 
  }
}
이러면 끝

0개의 댓글