종우의 컴퓨터 공간

XHR Object Methods & Working With Text File 본문

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

XHR Object Methods & Working With Text File

종우공간 2021. 8. 10. 08:45

<XMLHttpRequest object>.open(method, url, async?)

- initializes a newly-created request, or re-initializes an existing one

- parameters

  1. method: HTTP request method such as GET, POST, PUT, DELETE, etc
  2. url: a DOMString representing the URL to send the request to
  3. async?: an optional boolean parameter

<XMLHttpRequest object>.onprogress()

- onprogress() is the function called periodically with information when an XMLHttpReqeust before success completely

<XMLHttpRequest object>.onload()

- onload() is the functon called when an XMLHttpRequest transaction completes successfully

<XMLHttpRequest object>.onerror()

- onerror() is the function when an XMLHttpReqeust transaction fails due to an error

<XMLHttpRequest object>.send()

- send() sends the request to the server. If the request in asynchronous, this method returns as soon as the request is sent and the result is delivered using events.

예제

document.getElementById('button').addEventListener('click', loadData);

function loadData() {
  // Create an XHR Object
  const xhr = new XMLHttpRequest();

  // OPEN; readyState Value of 1
  xhr.open('GET', 'data.txt', true);

  // Optional - used for spinners/loaders; readyState Value of 3
  xhr.onprogress = function() {
    console.log('READYSTATE', xhr.readyState);
  }

  // this 'onload' gets called when everything gets ready; readyState Value already at 4
  xhr.onload = function() {
    if(this.status === 200) {
      document.getElementById('output').innerHTML = 
      `<h3>${this.responseText}</h3>`
    }
  }

  // this 'onerror' gets called when error
  xhr.onerror = function() {
    console.log('Request error...');
  }

  xhr.send();

  // readyState Values
  // 0: request not initialized
  // 1: server connection established
  // 2: request received
  // 3: processing request
  // 4: request finished and response is ready

  // HTTP statuses
  // 200; "OK"
  // 403: "Forbiden"
  // 404: "Not Found"
}

'자바 스크립트 (JavaScript) > Asynchronous JS, Ajax & Fetch API' 카테고리의 다른 글

Callback Functions  (0) 2021.08.11
REST API & HTTP Requests  (0) 2021.08.11
Data From an External API  (0) 2021.08.10
Working with Ajax & JSON  (0) 2021.08.10
★Ajax & XHR introduction  (0) 2021.08.10