TechScribe Notes

[코딩애플;JS]Ajax 본문

프론트엔드/JavaScript

[코딩애플;JS]Ajax

yunmee0704 2023. 11. 17. 21:55

💡서버란: 유저가 데이터 요청 시 데이터를 보내주거나 가져오는 간단한 프로그램

💡서버에 데이터를 요청할 때는 어떤 데이터인지 url을 기재하고, 어떤 방법으로 가져올지 결정해야함(get/post)

    -get은 데이터를 가져오고 싶을 때/  post 는 데이터를 전송하고 싶을 때.

   ->form태그에 직접 <form action="요청할url" method="post"> 이런식으로 해도 가능하지만

      단점은 브라우저가 새로고침 됨.

 

⭐AJAX는 서버에 GET, POST요청 시 새로고침 없이 데이터를 주고받을 수 있는 간단한 브라우저 기능.

 

 1️⃣Jquery로 가져오기

        .done(function(data){
          console.log(data)//성공했을때
        })
        .fail(function(error){
          console.log('실패함')//실패했을 때
        });

 

2️⃣JS로 가져오기

        .then(res => res.json())
        .then(function(data){
          console.log(data)
        })
        .catch(function(error){
          console.log('실패함')
        });
       

 

✍️서버와 데이터를 주고 받을 땐 문자만 주고 받을 수 있음.

     JSON은 객체 자료 값 전체에 ""를 다 치기 때문에 따로 원래 배열이나 객체자료롤 바꿔줘야함.

    Jquery의 $.get()은 알아서 바꿔주지만 JS는 불가능하므로  .then(res => res.json()) 코드 한줄이 더 필요함.

    아니면 axios 라이브러리 사용

 

3️⃣insertAdjacentHTML로 카드 한 줄 생성 후 그 이후로는 데이터 불러와서 생성하기.

    데이터를 다 불러오고 나면 더보기 버튼 안보이게 하

  <div class="container">
    <div class="row">

    </div>
    <button class="btn btn-danger">더보기</button>
  </div>
    integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous">
  </script>
  <script>
    var Products = [{
        id: 0,
        price: 70000,
        title: 'Blossom Dress'
      },
      {
        id: 1,
        price: 50000,
        title: 'Springfield Shirt'
      },
      {
        id: 2,
        price: 60000,
        title: 'Black Monastery'
      }
    ];



    var price = document.querySelectorAll('p');
    var title = document.querySelectorAll('h5');
    Products.forEach((a, i) => {
      var row = document.querySelector('.row');
      var card = ` <div class="col-sm-4">
        <img src="https://via.placeholder.com/600" class="w-100">
        <h5>${a.title}</h5>
        <p "class=price">가격 : ${a.price}</p>
       </div>  `
      row.insertAdjacentHTML('beforeend', card);


    });

    var num = 1;//num을 1로 변수 설정.
    document.querySelector('.btn').addEventListener('click', function () {

      fetch('https://codingapple1.github.io/js/more' + num + '.json')//누를 때마다 num의 번호가 바뀌면서
      //데이터 가져오는 url변경;
        .then(res => res.json())
        .then(function (data) {//데이터 가져오기 성공시
          data.forEach((a, i) => {
            var row = document.querySelector('.row');
            var card = ` <div class="col-sm-4">
          <img src="https://via.placeholder.com/600" class="w-100">
          <h5>${data[i].title}</h5>
          <p "class=price">가격 : ${data[i].price}</p>
        </div>  `
            row.insertAdjacentHTML('beforeend', card);


          });
        })
        .catch(function (error) {
          console.log('실패');
        })
        num+=1;//데이터불러오고 나서 num에 1을 더해줌
      if (num > 2) {
        document.querySelector('.btn').style.display = 'none';//more2.json밖에 없어서 2이상이면 보이지 않기기
      }
    })