04. ์๋ฒ์ ํต์ ํ๊ธฐ

๐ ๋ณต์ต ๋ด์ฉ

12-1. ์๋ฒ์ ์๋ JSON์๋ฃ ํ์
let xhr = new XMLHttpRequest();
const url="https://reqres.in/api/products/10";
const result=document.querySelector("#result");
xhr.open("GET",url);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState ==4 && xhr.status==200){
let goods = JSON.parse(xhr.responseText);
result.innerHTML=`
์ํ๋ช
: ${goods.data.name} <br/>
์์ฐ๋
๋:${goods.data.year}
`;
}
}

โ Point
JSON ์ฐ๊ฒฐํ๋ ๊ณผ์
12-2 try catch , throw
const userNumber=document.querySelector("#user-number");
const btn=document.querySelector("button");
const result=document.querySelector("#result");
btn.addEventListener("click",()=>{
console.log(userNumber.value);
try{
if(userNumber.value>10){
throw "10๋ณด๋ค ์์ ์๋ฅผ ์
๋ ฅํ์ธ์!"
}else{
result.innerHTML=`
${userNumber.value}
`;
}
}catch(err){
alert(err);
}
})

โ Point
try catch ๋ฌธ
throw "์๋ฌ๋ฉ์ธ์ง"
13. JSON์ ์ด์ฉํ ๋ช ์ธ ์ถ์ถ
const result=document.querySelector("#result");
const quotoDiv=document.querySelector(".quote");
const authorDiv=document.querySelector(".author");
fetch("https://dummyjson.com/quotes")
.then(response=>response.json())
.then(quoteList=>showQuote(quoteList));
function showQuote(a){
try{
let rdNum=Math.floor((Math.random()*a.quotes.length)+1)
quotoDiv.innerHTML=`${a.quotes[rdNum].quote}`;
authorDiv.innerHTML=`${a.quotes[rdNum].author}`;
}catch(err){
console.error(err);
}
}

โ Point
fetch().then().catch()
querySelector(selector)
selector์ ๊ตฌ์ฒด์ ์ธ ๊ทธ๋ฃน๊ณผ ์ผ์นํ๋ document์ ์ฒซ๋ฒ์งธ ์๋ฆฌ๋จผํธ๋ฅผ ๋ฐํํ๋ค.
์ผ์นํ๋๊ฒ ์์ผ๋ฉด null๋ฐํํ๋ค.
์ฐธ๊ณ ์ฌ์ดํธ
'๊ณต๋ถ ๊ธฐ๋ก โ๏ธ > Javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| Do-it! JS ์ค์ต ๋ณต์ต #unit 3 (0) | 2023.04.10 |
|---|---|
| Do-it! JS ์ค์ต ๋ณต์ต #unit2 (0) | 2023.04.07 |
| Do-it! JS ์ค์ต ๋ณต์ต #unit1 (0) | 2023.04.06 |
| JS-Do it! JS - #12์ผ (17,18) (0) | 2023.04.03 |
| JS-Do it! JS - #11์ผ (16) (0) | 2023.04.01 |