1. XMLHttpRequest를 사용한 방법
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
var data = JSON.stringify({
key1: 'value1',
key2: 'value2'
});
xhr.send(data);
2. Fetch API를 사용한 방법
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
fetch('https://example.com/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
key1: 'value1',
key2: 'value2',
}),
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
3. Axios 라이브러리를 사용한 방법
axios.get('https://example.com/api/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
axios.post('https://example.com/api/data', {
key1: 'value1',
key2: 'value2',
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
4. $.ajax 라이브러리를 사용한 방법
$.ajax({
url: 'https://example.com/api/data',
method: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
$.ajax({
url: 'https://example.com/api/data',
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({
key1: 'value1',
key2: 'value2'
}),
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
이 세 가지 방법 모두 널리 사용되며, 각각의 장단점이 있습니다.
XMLHttpRequest는 오래된 방법이지만 모든 브라우저에서 지원되고 있습니다.
Fetch API는 비교적 최근에 나왔으며 간결하고 강력한 기능을 제공합니다.
Axios는 HTTP 클라이언트 라이브러리로서 코드를 간결하게 작성할 수 있고 다양한 환경에서 사용할 수 있습니다.
ajax를 사용한 방식이 있습니다.
이를 통해 다양한 상황에 맞게 선택하여 사용할 수 있습니다.