Fetch starter

✓   웹의 동일출처 정책에 의해, 이 예제 코드는 여기서 바로 실행할 수 없다. 이 예제 문서와 가져올 소스는 같은 웹사이트 내에(프로토콜과 호스트 서버, 포트까지) 있어야 한다! 실제 작동 예 보러가기

            
                
            
        
            
                const mayChoose= document.querySelector("select")
                const poemDisplay= document.querySelector(".p_info_view")

                mayChoose.addEventListener("change", () => {
                    const may= mayChoose.value
                    updateDisplay(may)
                });

                function updateDisplay(may) {
                    may= may.replace(" ", "").toLowerCase() // 파일명의 공백을 없애고, 영문 대문자는 소문자로 변경한다
                    const url= `${may}.txt`

                    // fetch()에 URL을 전달하고, fetch()는 Promise를 반환한다: 
                    fetch(url).then((response) => { // 서버로부터 응답을 받았을 때, 응답과 함께 Promise의 .then() 핸들러가 호출된다
                        if(!response.ok) { // 요청에 성공하지 못했을 때
                            throw new Error(`HTTP error: ${response.status}`);
                        }

                        return response.text(); // 받아온 텍스트 데이터를 반환한다
                    }).then((text) => { // response.text()가 성공하면; `then()` 핸들러는 텍스트와 함께 호출되고,
                        poemDisplay.textContent= text //  이를 poemDisplay 박스에 출력한다
                    }).catch((error) => { // 에러가 발생하면; 
                        poemDisplay.textContent= `Could not fetch may: ${error}` // poemDisplay 박스에 에러 메시지를 표시한다
                    });
                }

                updateDisplay("오월 1")
                mayChoose.value= "오월 1"