๊ณต๋ถ€ ๊ธฐ๋ก โœ๏ธ/Javascript

Do-it! JS ์‹ค์Šต ๋ณต์Šต #unit 4 ๐Ÿค”

๋ฒ„๋‘˜ 2023. 4. 12. 10:58

04. ์„œ๋ฒ„์™€ ํ†ต์‹ ํ•˜๊ธฐ

 

๐Ÿ“– ๋ณต์Šต ๋‚ด์šฉ

์„œ๋ฒ„ ํ†ต์‹ 

 

๐Ÿ‘‰ fetch API


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๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

 

์ฐธ๊ณ ์‚ฌ์ดํŠธ

querySelector vs getElemenBytId