Fetch ๋๋ถ์ ๋ฐ๋๋ผJS๋ก ๊ฐ๋จํ๊ฒ Ajax๋ฅผ ์ฌ์ฉํ ์ ์๊ฒ ๋์๋ค๊ณ ํ๋ค.
์ด ์ ์ Ajax๋ฅผ ์ฌ์ฉํด ๋ณธ ์ ์ ์์ง๋ง ํ์คํ XMLHttpRequest ๋ณด๋ค๋ ๊ฐ๋จ
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<style>
table,th,td{
border: 2px solid;
border-collapse : collapse;
}
table{
width:80%;
margin:auto;
}
</style>
</head>
<body>
<h1>
Fetch API
</h1>
<br>
<table>
<caption>JSON ํ์ฑํด์ ํ ๋ง๋ค๊ธฐ</caption>
<tr>
<th>ID</th>
<th>title</th>
<th>body</th>
</tr>
</table>
<script>
//fetch('url')
//.then()์ ์๋ฒ์ ํต์ ํ response ๊ฐ์ฒด return
fetch('https://jsonplaceholder.typicode.com/posts').then(function(res){
res.json().then(function(json){
for(i=0;i<json.length;i++){
document.querySelector("table").innerHTML+=
"<tr>"+
"<td>" + json[i].id + "</td>"+
"<td> " +json[i].title +"</td>"+
"<td> " +json[i].body + "</td>"+
"</tr>";
}
})
})
</script>
</body>
</html>
json sample data -> jsonplaceholder.typicode.com
JSONPlaceholder - Free Fake REST API
{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB As of Dec 2020, serving ~1.8 billion requests each month.
jsonplaceholder.typicode.com
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
//JSON์์ฒญ์ stringify (API๋ช
์ธ์๋ฐ๋ผ JSON์
๋ ฅ)
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
//JSON์์ฒญ์ stringify (API๋ช
์ธ์๋ฐ๋ผ JSON์
๋ ฅ)
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then(function(res){
res.json().then(function(json){
console.log(json);
})
})
'๐ Programming > Web' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript] JQuery์ Ajax (0) | 2021.02.07 |
---|---|
[JavaScript] Ajax XMLhttpRequest (0) | 2021.02.07 |
[HTML] ๊ธฐ์ด์ ๋ฆฌ (0) | 2021.01.31 |
[HTML] table & list (0) | 2021.01.31 |