Ajax 비동기 통신에 대해서 정리
jQuery Ajax 문법 기본 형식
$.ajax(
{
type: "get",
url:"",
data: {
"index" : value
},
dataType: "text", //응답받을 값 타입
success: function(data, status, xhr){
console.log("data:", data);
},
error: function(xhr, status, e){
console.log(xhr.status);
}
}//json
);//ajax
url 경로 주의
데이터 보내기
json 형식의 "key": value 형식으로 전송
전달받는 곳에서 폼데이터처럼 사용가능
반환받는 데이터타입
응답해주는 곳에서 어떤 데이터를 어떤 타입으로 보낸지를 생각한 후에 해당 데이터값을 적절히 사용할 수 있는 데이터타입으로 설정
데이터 응답
기본적으로는 response객체의 getWriter()메소드를 통해 writer객체를 얻어 print()메소드로 값을 전달할 수 있음.
response.getWriter().print(value)
응답하기 전에 응답데이터의 타입에 맞게 response를 알맞게 인코딩해줘야함
res.setContentType("application/x-json; charset=utf-8")
res.setContentType("text/html; charset=UTF-8");
자바코드에서 json객체 생성 및 사용법
- json객체 생성
- json객체에 "이름"에 넣을 값을 설정해준다.
JSONObject jsonObj = new JSONObject(); jsonObj.put("list", list);
request.setCharacterEncoding("utf-8");
String userId = request.getParameter("userId");
MemberService service = new MemberService();
데이터타입 value = service.처리함수(userid)
response.setContentType("application/x-json; charset=utf-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(value)
참고글 : https://chlee21.tistory.com/158