JS) Fetch 사용법

소정·2024년 1월 30일

WEB_FRONT

목록 보기
20/20

배열로 답긴 값 json 형태로 변경하는 키워드

const orderToJson = JSON.stringify(orderData);

fetch : post로 보내기

fetch('컨트롤러 맵핑 주소', {
      method: 'POST',
      headers : {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: orderToJson, //json 형태로 보내기
    }).then(response => response.text())
            .then(data => {
              console.log('Success:', data);
            })
            .catch((error) => {
              console.error('Error:', error);
            });

fetch : get으로 보내고 json로 받기

fetch('/order/getList?tblNo='+tableNum)
            .then(response => response.json())  // 또는 response.json() 등으로 파싱
            .then(data => {
              const detailsContainer = document.querySelector('.details ul');
              detailsContainer.innerHTML = ''; // 기존의 내용 초기화
              // 데이터를 기반으로 동적으로 리스트 아이템 생성
              data.forEach(ord => {
                const listItem = document.createElement('li');
           					<div class="li-inner">
                                <p class="total">${new Intl.NumberFormat('ko-KR').format(ord.orderTotalPrice)}</p>
                            </div>
                `;

                detailsContainer.appendChild(listItem);
              });

          
            })
            .catch(error => {
              console.error('Error:', error);
            });
  }
profile
보조기억장치

0개의 댓글