본문 바로가기

프로그래밍/Javascript

[javascript] XMLHttpRequest를 사용하여 통신하기 (jQuery와 $.ajax 없이)

[GET 방식]

var xhr = new XMLHttpRequest();

xhr.open("GET", "your_url", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // success code here
    }
};
xhr.send();

 

[POST 방식]

var xhr = new XMLHttpRequest();
xhr.open("POST", "your_url", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // success code here
    }
};
xhr.send(JSON.stringify({data: "your_data"}));

 

 

출처 : GPT