โ AJAX (Asynchronous JavaScript and XML) ๋?
AJAX๋ ์ฌ๋ฌ ๊ธฐ์ ์ ์กฐํฉํ์ฌ ๋น๋๊ธฐ์ ์ผ๋ก ์๋ฒ์ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๋ฐฉ๋ฒ
โ Fetch API ๋?
Fetch API๋ AJAX์ ๋น์ทํ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ ์ต์ ์น API๋ก, ํ๋ก๋ฏธ์ค๋ฅผ ์ฌ์ฉํ์ฌ ๋น๋๊ธฐ ์์ฒญ์ ๋์ฑ ๊ฐ๊ฒฐํ๊ฒ ์ฒ๋ฆฌ
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
ํ์๋ฆฌํ๋ก ๋ง๋ค์ด์ง ๋ทฐ ์
๋๋ค.
<button type="button" id="getBtn">get๋ฐฉ์</button>
<button type="button" id="postBtn">post๋ฐฉ์</button>
<!--
<script>
var getBtn = document.getElementById("getBtn");
getBtn.addEventListener("click", function() {
fetch("/getData2/1/ํ๊ธธ๋")
.then(function(response) {
return response.text()
})
.then(function(data) {
console.log(data)
})
})
var postBtn = document.getElementById("postBtn");
postBtn.addEventListener("click", function() {
//post
fetch("/getEntity", {
method : "post",
headers : {
"Content-Type" : "application/json"
},
body : JSON.stringify({num : 1, name : "ํ๊ธธ๋"})
})
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
})
</script>
-->
<!-- ์ ์ด์ฟผ๋ฆฌ ๋งํฌ-->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#getBtn").click(function() {
$.ajax({
type : "get", //์์ฒญ๋ฐฉ์
url : "/getData2/1/์ด์์ ", //์์ฒญ์ฃผ์
success : function(data) {
console.log(data)
},
error: function(err, status) {
console.log(err)
}
})
})
$("#postBtn").click(function() {
$.ajax({
type : "post", //์์ฒญ๋ฐฉ์
url : "/getEntity", //์์ฒญ๋ฐฉ์
data : JSON.stringify({num : 1, name : "ํ์์"}), //๋ณด๋ผ๋ฐ์ดํฐ
contentType : "application/json", //๋ณด๋ผ๋ฐ์ดํฐ์ ๋ํ ํ์
dataType : "json", //์๋ฒ๊ฐ ๋ฆฌํดํ๋ ๋ฐ์ดํฐ ํ์
(์๋ต๊ฐ๋ฅ)
success : function(data) {
console.log(data);
},
error : function(err, status) {
console.log(err);
}
})
})
</script>
<button type="button" id="ex01">ex01</button>
<button type="button" id="ex02">ex02</button>
<script>
var ex01 = document.getElementById("ex01");
ex01.addEventListener("click", function() {
fetch("/api/v1/getData?sno=1&name=์ด์์ ")
.then(function(response) {
return response.json() //์๋ต json
})
.then(function(data) {
console.log(data)
})
})
var ex02 = document.getElementById("ex02");
ex02.addEventListener("click", function() {
fetch("/api/v1/getInfo", {
method : "post",
headers : {
"Content-type" : "application/json"
},
body : JSON.stringify({memo: "ํ๊ธธ๋123123", phone: "010-1234-1234"})
})
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
})
</script>
</body>
</html>