비동기 순서와 상관없이 실행된다.
npx json-server --watch db.json
서버열기
ajax 백그라운드에서 보이지 않게 서버와 통신하여 동적으로 해주는 기능을 말함
fetch
JSON.parse() 는 JSON 문자열의 구문을 JavaScript 값이나 객체로 생성한다.
JSON.parse(`[
{
"id": 1,
"title": "html",
"body": "html is ..."
},
{
"id": 2,
"title": "css",
"body": "css is ..."
}
]`)
JSON.stringify() 는 JavaScript 값이나 객체를 JSON 문자열로 변환
ex) JSON.stringify({ title: t, body: b })
fetch 사용하기 MDN
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch#json_%EB%8D%B0%EC%9D%B4%ED%84%B0_%EC%97%85%EB%A1%9C%EB%93%9C
fetch를 사용하면 promise가 리턴된다.
fetch를 사용해 json데이터 가져와 사용하기function showHexaCode(e) { e.preventDefault()
const userInputColor = inputElem.value
fetch('data.json') //json파일 경로를 넣는다.
.then(response => response.json())
.then(datas => {
// 배열의 요소 중, color 가, 사용자가 입력한 색과 일치하는 요소를 찾음.
const foundData = datas.find(data => data.color === userInputColor)
hexaCodeElem.innerHTML = foundData.value
hexaCodeElem.style.color = foundData.value
})
}
const inputElem = document.querySelector('#inputColor')
const buttonElem = document.querySelector('#buttonSubmit')
const hexaCodeElem = document.querySelector('#hexaCode')
buttonElem.addEventListener("click", showHexaCode)
json파일 data.json
[
{
"color": "red",
"value": "#f00"
},
{
"color": "green",
"value": "#0f0"
}
]