Ajax(Asynchronous Javascript And XML)란 자바스크립트를 이용해 서버와 브라우저가 비동기 방식으로 데이터를 교환할 수 있는 통신 기능이다. 서버측으로 다양한 형식(JSON, XML, HTML 및 일반 텍스트 형식 등)의 정보를 주고 받을 수 있다.
비동기 방식이란? 웹페이지를 리로드하지 않고 데이터를 불러오는 방식이다.
*JSON.stringify(): JavaScript 값이나 객체(object)를 'JSON의 문자열'로 변환
$.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"
},
contentType : "전송할 데이터 타입", //기본 값 : "application / x-www-form-urlencoded; charset = UTF-8"
dataType : 'text', // 서버로 부터 수신할 데이터 타입 (html, xml, json, text 등등)
data : JSON.stringify({ // 서버에 전송할 데이터 (Object , String, Array)
"data1" : 1,
"data2" : 2
}),
success : function(result) { // 결과 성공 콜백함수
console.log(result);
},
error : function(request, status, error) { // 결과 에러 콜백함수
console.log(error)
}
})
$.ajax( "/text",
{
method: 'get',
data : { name: "chan" },
dataType: 'json'
}
)
.done(function() { // 서버요청이 성공시의 콜백함수
alert( "success" );
})
.fail(function() { // 서버요청이 에러시의 콜백함수
alert( "error" );
})
.always(function() { // 항상 실행 (finally 같은느낌)
alert( "complete" );
});