λΉλκΈ° ν΅μ μ μν AJAX, XML, JSON 2ν
Front-End
2023.07.19.
βοΈ μλκΈ κ³ λκ³Ό μκ²½μ λ 2
xhr.readyState
xhr.readyState | μ€λͺ |
---|---|
0 | open() λ©μλ νΈμΆ μ |
1 | send() λ©μλ νΈμΆ μ |
2 | send() λ©μλλ₯Ό νΈμΆνμΌλ μμ§ μλ²μ μλ΅μ λ°μ§ λͺ»ν μν |
3 | send() λ©μλλ₯Ό νΈμΆνκ³ μλ²μ μλ΅μ μΌλΆ λ°μ μν |
4 | send() λ©μλλ₯Ό νΈμΆνκ³ μλ²μ μλ΅μ΄ μλ£λ μν |
β μλ²κ° μλ΅μ μμ²ν λ StatusCodeλ₯Ό 첨λΆν©λλ€.
xhr.status
StatusCode | μ€λͺ |
---|---|
1xx | μ²λ¦¬ μ€, μ μ§ μ€ |
100 continue | |
2xx | μ±κ³΅ |
200 ok | |
3xx | 리λ€μ΄λ νΈ |
302 redirect | |
4xx | ν΄λΌμ΄μΈνΈ μ€λ₯ |
404 not found | |
5xx | μλ² μ€λ₯ |
500 internal server error |
ν΄λΌμ΄μΈνΈκ° μλ²μ λΆμκ²μ΄ μ±κ³΅ν μ½λ : xhr.readyState: 4 And xhr.status: 200
β event: readystatechange
ajax μμ
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', ajaxHandler);
function ajaxHandler() {
if (xhr.readyState === 4 && xhr.status === 200) {
var personsChild = parsePersonsJSON(xhr.responseText);
var persons = document.querySelector('#persons');
persons.innerHTML = '';
for (var i in personsChild) {
persons.appendChild(personsChild[i]);
}
}
}
function parsePersonsJSON(jsonStr) {
var persons = JSON.parse(jsonStr);
for (var i in persons) {
var content = '<h4>μ΄λ¦: ' + persons[i].name + '</h4>';
content += '<h4>μ±λ³: ' + persons[i].gender + '</h4>';
content += '<h4>λμ΄: ' + persons[i].age + '</h4>';
content += '<h4>λΆμΌ: ' + persons[i].field + '</h4>';
var div = document.createElement('div');
div.setAttribute('class', 'person');
div.innerHTML = content;
persons[i] = div;
}
return persons;
}
function sendHandler() {
xhr.open('GET', 'persons.json', true);
xhr.send();
}
function clearHandler() {
document.querySelector('#persons').innerHTML = '';
}
function init() {
document.querySelector('#send').addEventListener('click', sendHandler);
document.querySelector('#clear').addEventListener('click', clearHandler);
}
window.addEventListener('load', init);