./categories/front-end
JavaScript·jQuery Ajax
개요
비동기 HTTP로 화면 전체 갱신 없이 서버와 데이터 교환.
데이터 형식
- CSV: 용량 작음, 가독성 낮음
- XML: 태그 구조, 용량 큼
- JSON: JS 객체 형태(현재 주류)
HTTP 메소드
GET(조회) / POST(생성·수정) / PUT / DELETE / HEAD
XHR
var xhr = window.XMLHttpRequest
? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP"); // IE7 이하
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// 성공
}
};
xhr.open("GET", "exam.xml", true);
xhr.send();
JSON.parse(xhr.responseText);
readyState: 0~4 (4=완료)status: 200 성공 / 403 / 404 / 500
jQuery
$(selector).load(URL, DATA, CALLBACK);
$('#dictionary').load("load.html");
$(selector).load('exam.html img'); // 특정 태그만
$.ajax({
url: 'ajax.xml', type: 'GET', dataType: 'xml',
success: function(data) {
$('#dictionary').empty();
$.each($(data).find('entry'), function() {
var $entry = $(this);
$('#dictionary').append('<div>' + $entry.attr('term') + '</div>');
});
}
});
// 옵션: url, data, type, dataType, success, error, complete, beforeSend, async
$.get(URL, DATA, CALLBACK);
$.post(URL, DATA, CALLBACK);
$.getJSON(URL, DATA, CALLBACK);
$.getScript(URL);
관련 링크: http://www.nextree.co.kr/p9521/
./comments