1. Ajax
1-1) Ajax
Asynchronous Javascript(비동기 자바스크립트) + XML의 의미로 자바스크립트를
사용한 비동기 통신
즉, 클라이언트와 서버 간의 XML이나 JSON 데이터를 주고받는 기술을 의미함.
Ajax는 페이지 이동 없이 데이터 처리가 가능하며,
서버의 처리를 기다리지 않고 비동기 요청이 가능하다는 특징.
1-2) Ajax 웹 페이지 동작
Ajax로 페이지를 처리하는 경우를 보면 요청 페이지의 결과를 서버에서 처리한 후
다시 XML이나 JSON으로 원래 요청 페이지로 전송함. 즉, 페이지 이동이 발생하지 않음.
이러한 비동기성을 통해 사용자의 Event가 있으면 전체 페이지가 아닌
일부분만을 업데이트 할 수 있게 해줍니다.
2. Ajax 문법 (JQuery기준)
2-1) Ajax 옵션(JQuery 기준)
2-2) Ajax 문법(JQuery 기준)
$.ajax({
type : 'post', // 타입 (get, post, put 등등)
url : '/test', // 요청할 서버url
async : true, // 비동기화 여부 (default : true)
headers : { // Http header
"Content-Type" : "application/json",
"X-HTTP-Method-Override" : "POST"
},
dataType : 'text', // 데이터 타입 (html, xml, json, text 등등)
data : JSON.stringify({ // 보낼 데이터 (Object , String, Array)
"no" : no,
"name" : name,
"nick" : nick
}),
success : function(result) { // 결과 성공 콜백함수
console.log(result);
},
error : function(request, status, error) { // 결과 에러 콜백함수
console.log(error)
}
})
2-3) $.getJson()
$.getJSON( url [, data] [, success] ) {}
// $.getJSON는 아래 ajax함수의 약자 이다.
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
2-3) $.post()
$.post( url [, data ] [, success ] [, dataType ] ) {}
// $.post는 아래 ajax 함수의 약자이다.
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
3. Ajax(최신 버전의 Ajax 방법)
$.ajax( "/text",
{
method: 'get',
data : { name: "chan" },
dataType: 'json'
}
)
.done(function() { // 서버요청이 성공시의 콜백함수
alert( "success" );
})
.fail(function() { // 서버요청이 에러시의 콜백함수
alert( "error" );
})
.always(function() { // 항상 실행 (finally 같은느낌)
alert( "complete" );
});