Jassy 2020. 8. 31. 17:12

https://opentutorials.org/course/3281/20565

 

Ajax

 

- 외부에 있는 데이터를 가져와서 사용할 수 있다. 

- 변경이 용이하다 

 

예를들어, 인터넷 쇼핑몰 에서 아우터, 상의, 하의 구분에 따라 내용이 다르지만

기초적인 포멧 (메뉴 구성)은 같다고 할 때, 

ajax를 이용해 쉽고 빠르게 필요한 아우터or상의or하의 데이터를 불러오고

메뉴에 오타가 있다고 할때, ajax 파일 하나만 수정하면 됨. 

또는 

세계시간 사이트에서 세계시간 정보를 ajax로 퍼와서 내 홈페이지에 그대로 나오게 할 수 잇음. 

 

 

 

response에 대해, 

response는 웹사이트에 접근이 가능한지 아닌지에 대한 데이터를 담고 있음. 

202로 떳을 때 -> 접근 가능

404 -> 접근 불가능 

 


HTTP 요청에는 여러 유형이 있습니다. 

가장 일반적으로 사용되는 4 가지 유형의 HTTP 요청은 GET, POST, PUT 및 DELETE입니다. 

 

GET 요청을 통해 일부 소스 (일반적으로 웹 사이트)에서 정보를 검색하거나 가져 옵니다. 

POST 요청의 경우 정보를 처리하고 다시 보낼 소스에 정보를 게시 합니다.

 


1. XHR GET 요청 I 

 

 

AJAX (Asynchronous JavaScript and XML)를 사용하면 초기 페이지로드 후에 요청할 수 있습니다. 

처음에는 AJAX가 XML 형식의 데이터에만 사용되었지만

이제는 다양한 형식을 가진 요청을 만드는 데 사용할 수 있습니다.

 

MDN 문서 : XML (Extensible Markup Language) .

 

XML introduction

XML (Extensible Markup Language) is a markup language similar to HTML, but without predefined tags to use. Instead, you define your own tags designed specifically for your needs. This is a powerful way to store data in a format that can be stored, searched

developer.mozilla.org

 

마찬가지로 XML의 이름 인 XMLHttpRequest (XHR) API를 사용하여 여러 종류의 요청을 만들고 다른 형식의 데이터를 지원할 수 있습니다.

 

 

// While the code will work regardless of how you name your variables, it is a common practice to name this object xhr
const xhr = new XMLHttpRequest() ;

const url = 'https://api-to-call.com/endpoint';

//JSON is JavaScript Object Notation, which is how the response is going to be formatted
xhr.responseType = 'json';

xhr.onreadystatechange = ( ) => {
  //The purpose of this conditional statement checks to see if the request has finished.//
  if (xhr.readyState === XMLHttpRequest.DONE) {
  //To access the response property, we can use dot notation like so: xhr.response. This response will contain the data that we’re getting back from the request.
    return xhr.response;
}
}

//.open() creates a new request and the arguments passed in determine the type and URL of the request.
xhr.open('GET',url);
xhr.send();

 

 

 

쿼리 문자열에는 요청과 함께 보낼 추가 정보가 포함됩니다. Datamuse API를 사용하면 요청 URL에 연결된 쿼리 문자열을 사용하여보다 구체적인 데이터를 검색 할 수 있습니다.

 

쿼리 문자열은 ?문자를 사용하여 URL과 구분됩니다 .  ?, 당신은 다음에 합류 키 값 쌍입니다 매개 변수를 만들 수 있습니다 =. 아래 예를 살펴보십시오.

 

'https://api.datamuse.com/words?key=value'

추가 매개 변수를 추가하려면 &문자를 사용 하여 매개 변수를 구분해야합니다. 이렇게 :

'https://api.datamuse.com/words?key=value&anotherKey=anotherValue'

 


 2. XHR POST 

 

GET 요청과 POST 요청의 주요 차이점은 POST 요청에는 요청을 통해 전송되는 추가 정보가 필요하다는 것입니다. 

이 추가 정보는 게시 요청 본문  전송됩니다 .

 

 
 const xhr = new XMLHttpRequest ;
 const url = 'https://api-to-call.com/endpoint';

 //JSON.stringify()값을 JSON 문자열로 변환합니다. 값을 문자열로 변환하여 데이터를 서버로 보낼 수 있습니다.
 const data = JSON.stringify({id: '200'});

 xhr.responseType = 'json';
 xhr.onreadystatechange = () => {
  if(xhr.readyState === XMLHttpRequest.DONE){
      return xhr.response ;
    }
 }

 xhr.open('POST', url); 
 xhr.send(data);

 

 

//helperFunction.js

// Information to reach API
const apiKey = '<67dc48063f604d9ca8f0a4ee7c179e17>';
const url = 'https://api.rebrandly.com/v1/links';

// Some page elements
const inputField = document.querySelector('#input');
const shortenButton = document.querySelector('#shorten');
const responseField = document.querySelector('#responseField');

// AJAX functions
const shortenUrl = () => {
  const urlToShorten = inputField.value;
  const data = JSON.stringify({destination: urlToShorten});
  const xhr = new XMLHttpRequest ;
  xhr.responseType = 'json';
  xhr.onreadystatechange = () => {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    renderResponse(xhr.response);
  }
}
  xhr.open('POST', url);
  xhr.setRequestHeader('Content-type', 'application/json');
  xhr.setRequestHeader('apikey', apiKey);
  xhr.send(data)
}


// Clear page and call AJAX functions
const displayShortUrl = (event) => {
  event.preventDefault();
  while(responseField.firstChild){
    responseField.removeChild(responseField.firstChild);
  }
  shortenUrl();
}

shortenButton.addEventListener('click', displayShortUrl);

//main.js

// Information to reach API
const apiKey = '<67dc48063f604d9ca8f0a4ee7c179e17>';
const url = 'https://api.rebrandly.com/v1/links';

// Some page elements
const inputField = document.querySelector('#input');
const shortenButton = document.querySelector('#shorten');
const responseField = document.querySelector('#responseField');

// AJAX functions
const shortenUrl = () => {
  const urlToShorten = inputField.value;
  const data = JSON.stringify({destination: urlToShorten});
  const xhr = new XMLHttpRequest ;
  xhr.responseType = 'json';
  xhr.onreadystatechange = () => {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    renderResponse(xhr.response);
  }
}
  xhr.open('POST', url);
  xhr.setRequestHeader('Content-type', 'application/json');
  xhr.setRequestHeader('apikey', apiKey);
  xhr.send(data)
}


// Clear page and call AJAX functions
const displayShortUrl = (event) => {
  event.preventDefault();
  while(responseField.firstChild){
    responseField.removeChild(responseField.firstChild);
  }
  shortenUrl();
}

shortenButton.addEventListener('click', displayShortUrl);