생활코딩/JavaScript

200810 JavaScript - Ajax 1일차

imname1am 2020. 8. 10. 21:46
반응형

fetch API 기본 사용법

1) 경고창

<!doctype html>
<html>
    <body>
        <input type="button" value="fetch" onclick="
        fetch('html').then(function(response){
            response.text().then(function(text){
                alert(text);
            })
})
">
    </body>
</html>
fetch('html') ; html 파일에 있는 내용 경고창으로 띄우고 싶으면 '
alert(text) ; 모든 작업이 끝난 후 호출. text 변수 안에는 서버가 응답한 데이터가 들어있음

2) 웹페이지의 내용 바꾸고 싶을 때

<!doctype html>
<html>
    <body>
        <article>

        </article>
        <input type="button" value="fetch" onclick="
        fetch('html').then(function(response){
            response.text().then(function(text){
                document.querySelector('article').innerHTML = text;
            })
        })
    ">
    </body>
</html>

fetch API의 요청과 응답

fetch('html');

: fetch 함수 ; 첫 번째 인자로 전달된 데이터를 서버에게 요청.

Asynchronous (비동기적) ; 동시에 실행. 병렬적.

 

fetch API - response 객체

1) 둘 다 같은 의미의 함수.

function callmeback() {
    console.log('response end');
}
callmeback = function(){
    console.log('response end');
}

2) 익명함수 사용할 때;

1번에 나온 함수의 정의를 한 번에 할 수도 있음 (그냥 callmeback 정의 넣으면 됨.)

fetch('html').then(callmeback);
fetch('html').then(function(){
    console.log('response end');
});

생활코딩 Ajax

반응형