본문 바로가기
JSP/이론

콜백함수?//fetch (ajax 새로운 함수) //람다식

by SEOKIHOUSE 2023. 7. 14.
  • 콜백함수 - 다른 코드의 인수로서 넘겨주는 실행 가능한 코드

이런느낌이다

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="btn" onclick="f('aaaa')">run1</button>
    <button id="btn2" onclick="f2(f1, 'kkkk')">run2</button>

    <hr>
    <p id="demo"></p>

    <script>
        // const btn = document.getElementById("btn");
        // btn.addEventListener("click", f);

        function f(str) {
            alert("f()....." + str);
        }

        function f1(str) {
            document.querySelector("#demo").innerHTML = str;
        }

        function f2(func, s) {
            func(s);
        }
    </script>

</body>

</html>

  • fetch then then  -fetch 함수는 AJAX 요청을 수행하는 데 사용되는 기능

https://yeri-kim.github.io/posts/fetch/참고사이트

 

  • fetch(데이터를 받고)
          .then(응답이 온걸 text로)
          .then(text를 value로 넘겨주면 demo에 적힌다)
  • fetch 함수는 기본적으로 GET 요청을 보내는데 사용되므로, method 옵션을 설정하지 않으면 자동으로 GET 요청이 전송

 

https://jsonplaceholder.typicode.com/ 이 사이트를 가서 아래그림 복사

 

여기 데이터중 아무거나 눌러서 주소 복사 후 fetch에 넣자


  • fetch text로 해보자

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="btn" onclick="f()">run1</button>
    
    <hr>
    <p id="demo"></p>

    <script>
        const btn = document.querySelector("#btn");
        btn.addEventListener("click", f);

        function f() {
            fetch('https://jsonplaceholder.typicode.com/users')
                .then(resp => resp.text())
                .then(value1 => document.getElementById("demo").innerHTML = value1)
        }

    </script>
</body>

</html>

  • fetch json으로 해보자

parse안해줘도 되더라..

객체에 접근했기 때문에(value)[0].username했는데 

객체가 아니라면 그냥 (value)[0]써서 접근해주면 된다

 

 

'JSP > 이론' 카테고리의 다른 글

maven  (0) 2023.07.14
fetch post방식  (0) 2023.07.14
람다식  (0) 2023.07.14
카카오 map api  (0) 2023.07.06
JUnit(단위테스트 도구)//assertEquals  (0) 2023.07.04