1.사용자가 입력한 값을 변수에 저장합니다.
2.XMLHttpRequest 객체를 생성하고, 서버에 대한 요청을 설정합니다.
3.send() 메서드를 사용하여 서버로 요청을 보냅니다.
3.서버에서의 응답을 기다립니다. 응답이 도착하면 onload 이벤트 핸들러가 호출됩니다. 이때 응답이 성공적으로 처리되었는지 확인하고, 그에 따른 작업을 수행합니다.
4.만약 요청 중(보내는거 받는거 둘 다)에 네트워크 오류가 발생하면 onerror 이벤트 핸들러가 호출됩니다. 이 경우 네트워크 오류에 대한 처리를 수행합니다.
※ this.responseText: XMLHttpRequest 객체의 응답으로 받은 텍스트 데이터를 나타냅니다. 이 데이터는 일반적으로 서버로부터의 응답 내용을 포함하고 있습니다.
EX)
function saveRow(id) {
let name = document.getElementById(`edit-name-${id}`).value;
let email = document.getElementById(`edit-email-${id}`).value;
let age = document.getElementById(`edit-age-${id}`).value;
let xhr = new XMLHttpRequest();
xhr.open("POST", "update.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (this.status == 200) {
try {
let response = JSON.parse(this.responseText);
if (response.success) {
document.getElementById(`name-${id}`).innerText = name;
document.getElementById(`email-${id}`).innerText = email;
document.getElementById(`age-${id}`).innerText = age;
document.getElementById(`action-${id}`).innerHTML =
`<button onclick="editRow(${id})">편집</button>` +
`<button onclick="deleteRow(${id})">삭제</button>`;
} else {
alert('오류: ' + response.message);
}
} catch (e) {
alert('응답 처리 중 오류가 발생했습니다.');
}
}
};
xhr.onerror = function() {
alert("요청 중 오류가 발생했습니다.");
};
xhr.send(`id=${id}&name=${name}&email=${email}&age=${age}`);
}