Recent Posts
Recent Comments
Link
06-28 05:11
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

jquery ajax post 예제 본문

DEV&OPS/Javascript

jquery ajax post 예제

ALEPH.GEM 2022. 4. 19. 13:48

기본 예제

$.post("test.jsp");

데이터를 같이 전달하는 예제

$.post("test.jsp", {name: "john", time: "10:00pm"});

배열을 parameter로 전달하는 예제

$.post("test.jsp"), {'choices[]':["john", "susan"]});

폼(form) 데이터를 전달

$.post("test.jsp", $("testform").serialize());

콜백함수를 통한 리턴 값을 얻어와 알림창 출력

$.post("test.jsp", function(data){ alert(data);});

parameter로 데이터를 전달하고 콜백으로 리턴된 결과를 알림창으로 출력

$.post('test.jsp", 
	{name:"john", time:"10:00pm"}, 
   	function(data){ 
    		alert(data);
    	});

parameter로 데이터를 전달하고 json 형태의 데이터를 리턴받아 알림창으로 출력

$.post{"test.jsp", 
	{"func": "getNameAndTime"}, 
	function(data){ 
    		alert(data.name); 
        	alert(data.time);
        }, 
	"json");

 

jQuery ajax 예제와 서버 사이드 코드

$.ajax({
	type : "POST",
	url : "http://localhost/example.do", //요청 할 URL
	data : { test:'test'}, //넘길 파라미터
	contentType: "text/plain; charset=utf-8",
	jsonp : "callback",
	dataType : "jsonp",
	withCredentials: true,
	success : function(data) {
		//통신이 정상적으로 되었을때 실행 할 내용
		if(data != null)    {
			if(data.flag == "success"){
				console.log(data.message);
			}else{
				console.log(data.message);
			}
		}

	},
	error : function(data) {
		console.log("접속 도중 오류가 발생했습니다."); //에러시 실행 할 내용
	}
});
@RequestMapping("/example.do")
public void userCheck(HttpServletRequest req, HttpServletResponse rep, HttpSession session) throws IOException{
	rep.setContentType("text/plain; charset=utf-8");
	String test = new String(ServletRequestUtils.getStringParameter(req, "test", "").getBytes("8859_1"),"UTF-8");
	String callback = ServletRequestUtils.getStringParameter(req, "callback", "");

	//중간생략

	out.println(callback+"(");    //javascript(JSON) 객체를 callback(클라이언트 callback과 이름이 동일하도록) 으로 감싸줍니다.
	out.println("{\"flag\": \"success\", \"message\": \"실행 성공.\"}");
	out.println(")");

}

 

 

 

 

 

 

 

DEV

 

728x90

'DEV&OPS > Javascript' 카테고리의 다른 글

javascript check box 다루기  (2) 2022.04.19
javascript 로 select box option 다루기 예제  (0) 2022.04.19
javascript Web Workers  (0) 2022.03.21
javascript BLOB  (0) 2022.03.18
javascript 드래그 앤 드롭  (0) 2022.03.17