Teknik Request POST dan GET
Desember 31, 2020
METHOD XMLHttpRequest()
Request POST
var xhr = new XMLHttpRequest();
xhr.open('POST', '/', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({
"data": ""
}));
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
};
};
Request GET
var xhr = new XMLHttpRequest();
xhr.open('GET', '/', true);
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
};
};
xhr.send();
METHOD fetch()
Fetch POST
fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"data": ""
}),
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
Fetch GET
Jika respon adalah dalam bentuk JSON
fetch('/')
.then(response => response.json())
.then(function (data) {
console.log(data)
});
Jika respon dalam bentuk teks
fetch('/')
.then(response => response.text())
.then(function (data) {
console.log(data)
});