종우의 컴퓨터 공간

Working with Ajax & JSON 본문

자바 스크립트 (JavaScript)/Asynchronous JS, Ajax & Fetch API

Working with Ajax & JSON

종우공간 2021. 8. 10. 15:07
document.getElementById('button1').addEventListener('click', loadCustomer);
document.getElementById('button2').addEventListener('click', loadCustomers);

// Load Customer
function loadCustomer(e) {
  const xhr = new XMLHttpRequest();

  xhr.open('GET', 'customer.json', true);

  xhr.onload = function() {
    if(this.status === 200) {
      // console.log(this.responseText);

      const customer = JSON.parse(this.responseText);

      const output = `
      <ul>
        <li>Id: ${customer.id}</li>
        <li>Name: ${customer.name}</li>
        <li>Company: ${customer.company}</li>
        <li>Phone: ${customer.phone}</li>
      </ul>
      `;

      document.getElementById('customer').innerHTML = output;
    }
  }

  xhr.send();
}

// Load Customers
function loadCustomers(e) {
  const xhr = new XMLHttpRequest();

  xhr.open('GET', 'customers.json', true);

  xhr.onload = function() {
    if(this.status === 200) {
      // console.log(this.responseText);

      const customers = JSON.parse(this.responseText);

      let output = '';

      customers.forEach(function(customer) {
        // need to append to the output
        output += ` 
        <ul>
          <li>Id: ${customer.id}</li>
          <li>Name: ${customer.name}</li>
          <li>Company: ${customer.company}</li>
          <li>Phone: ${customer.phone}</li>
        </ul>
        `;
      })

      document.getElementById('customers').innerHTML = output;
    }
  }

  xhr.send();
}

- JSON.parse(<String value>): <String value>를 JSON 형태로 바꾼다.

- <xhr object>.status: 서버에서 가져온 status가 어떤지 반환한다.

- <xhr object>.responseText: open()할 때 사용한 파일의 값을 String으로 가져온다.