- async / await
- fetch
- axios
- insertAdjacentHTML
- 데이터 출력 예제
1) async / await
const test = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('1번 실행');
resolve();
}, 2000);
});
};
const test1 = () => console.log('2번 실행');
console.log('시작');
const make = async () => {
await test();
test1();
}
make();
시작
1번 실행
2번 실행
async은 Promise 기반이라고 생각하면 된다. await는 async가 처리 될 때 까지 기다린 후 실행된다.
따라서 위 코드를 실행시키면 시작이 출력되고, 2초 뒤에 1번 실행, 2번 실행이 출력되게 된다.
2) fetch
// data1
{
"userId" : 1,
"name" : "김",
"age" : 30,
"addr" : "서울"
}
fetch('./data/data1.json')
.then(res=>res.json())
.then(res=>console.log(res))
fetch는 아래와 같이 작성한다.
fetch('파일경로', 옵션)
.then((응답완료) => 응답완료.json())
.then((json받음) => console.log(받은 json파일 출력));
html을 실행한 후 console을 확인하면 위와 같이 data1파일이 잘 불러와 진 것을 볼 수 있다.
3) axios
axios의 경우 아래와 같이 작성한다.
axios.get('url', 옵션)
.then(응답완료=>응답완료 값)
<script>
axios.get('./data/data1.json')
.then(res=>console.log(res))
</script>
여기서 data 값만 출력하고 싶으면 res의 data를 불러오면 된다.
<script>
axios.get('./data/data1.json')
.then(res=>console.log(res.data))
</script>
4) insertAdjacentHTML
html을 문서에 삽입할 때 사용하는 메서드이다.
// data2.html
<h1 class="text">안녕하세요 비동기처리</h1>
<h2 class="text">Ajax 소개</h2>
<h3 class="text">axios / fetch</h3>
<body>
<button class="btn">문서 불러오기</button>
<div class="box">
<p>데이터 불러오기</p>
</div>
<script>
const btn = document.querySelector('.btn');
const box = document.querySelector('.box');
btn.addEventListener('click', e => {
const url = './data/data2.html'
fetch(url)
.then(res => res.text())
.then(text => box.insertAdjacentHTML('beforeend', text))
})
</script>
</body>
5) 데이터 출력 예제
// data3.json
{
"item" : [
{ "id" : 1, "name" : "김", "age" : 20, "addr" : "서울"},
{ "id" : 2, "name" : "이", "age" : 30, "addr" : "인천"},
{ "id" : 3, "name" : "박", "age" : 20, "addr" : "수원"},
{ "id" : 4, "name" : "최", "age" : 40, "addr" : "수원"},
{ "id" : 5, "name" : "윤", "age" : 50, "addr" : "서울"},
{ "id" : 6, "name" : "정", "age" : 10, "addr" : "서울"},
{ "id" : 7, "name" : "안", "age" : 20, "addr" : "인천"},
{ "id" : 8, "name" : "채", "age" : 30, "addr" : "시흥"},
{ "id" : 9, "name" : "고", "age" : 60, "addr" : "안산"},
{ "id" : 10, "name" : "금", "age" : 40, "addr" : "서산"}
]
}
<body>
<div class="box">
<table>
<caption>학생명단</caption>
<colgroup>
<col class="w1">
<col class="w2">
<col class="w3">
<col class="w4">
</colgroup>
<thead>
<tr>
<th>번호</th>
<th>이름</th>
<th>나이</th>
<th>주소</th>
</tr>
</thead>
<tbody class="table-tbody">
<!-- 생성후 데이터 출력 -->
</tbody>
</table>
</div>
<script>
const tbody = document.querySelector('.table-tbody')
fetch('./data/data3.json')
.then(res => res.json())
.then(data => {
for (let i = 0; i < data.item.length; i++) {
let tr = document.createElement('tr')
let td = document.createElement('td')
td.textContent = data.item[i].id
tr.append(td)
td = document.createElement('td')
td.textContent = data.item[i].name
tr.append(td)
td = document.createElement('td')
td.textContent = data.item[i].age
tr.append(td)
td = document.createElement('td')
td.textContent = data.item[i].addr
tr.append(td)
tbody.append(tr)
}
})
</script>
</body>
json파일에 배열 형식으로 담은 data를 fetch를 사용해 불러왔다.
출력될 부분은 tbody이므로 tbody에 tr과 td를 생성하고 append해주었다.
<body>
<div class="box">
<table>
<caption>학생명단</caption>
<colgroup>
<col class="w1">
<col class="w2">
<col class="w3">
<col class="w4">
<col class="w5">
</colgroup>
<thead>
<tr>
<th>번호</th>
<th>이름</th>
<th>나이</th>
<th>주소</th>
<th>관리</th>
</tr>
</thead>
<tbody class="table-tbody">
<!-- 생성후 데이터 출력 -->
</tbody>
</table>
<div class="btn">
<button class="allDel">전체 삭제</button>
<button class="allRe">전체 복구</button>
</div>
</div>
<script>
const tbody = document.querySelector('.table-tbody')
const allDel = document.querySelector('.allDel')
const allRe = document.querySelector('.allRe')
let tableDel = document.querySelectorAll('.tableDel')
fetch('./data/data3.json')
.then(res => res.json())
.then(data => {
function make() {
tbody.innerHTML = ""
for (let i = 0; i < data.item.length; i++) {
let tr = document.createElement('tr')
let td = document.createElement('td')
td.textContent = data.item[i].id
tr.append(td)
td = document.createElement('td')
td.textContent = data.item[i].name
tr.append(td)
td = document.createElement('td')
td.textContent = data.item[i].age
tr.append(td)
td = document.createElement('td')
td.textContent = data.item[i].addr
tr.append(td)
td = document.createElement('td')
td.innerHTML = '<button class="tableDel">삭제</button>'
tr.append(td)
tbody.append(tr)
del();
}
}
function del(){
tableDel = document.querySelectorAll('.tableDel')
tableDel.forEach(del => {
del.addEventListener('click', e => {
e.target.parentElement.parentElement.remove();
})
})
}
allDel.addEventListener('click', e => {
tbody.innerHTML = ""
})
allRe.addEventListener('click', e => {
make();
})
make();
del();
})
</script>
</body>
table에 관리 th를 하나 추가하고 innerHTML로 추가된 td에 button을 넣어주었다.
tbody에 추가하는 함수와 삭제버튼 함수를 따로 만들어 코드를 줄였다.