종우의 컴퓨터 공간
Data From an External API 본문
자바 스크립트 (JavaScript)/Asynchronous JS, Ajax & Fetch API
Data From an External API
종우공간 2021. 8. 10. 15:36document.querySelector('.get-jokes').addEventListener('click', getJokes);
function getJokes(e) {
const number = document.querySelector('input[type="number"]').value;
const xhr = new XMLHttpRequest();
// get it from the external API
xhr.open('GET', `http://api.icndb.com/jokes/random/${number}`, true);
xhr.onload = function() {
if (this.status === 200) {
const response = JSON.parse(this.responseText);
let output = '';
if (response.type === 'success') {
response.value.forEach(function(joke) {
output += `<li>${joke.joke}</li>`
})
} else {
output += '<li>Something went wrong</li>';
}
document.querySelector('.jokes').innerHTML = output;
}
}
xhr.send();
e.preventDefault();
}
- external API를 사용하기 위해서는 해당하는 URI를 xhr.open()의 두번째 퍼레미터에 넣어주면 된다.
'자바 스크립트 (JavaScript) > Asynchronous JS, Ajax & Fetch API' 카테고리의 다른 글
Callback Functions (0) | 2021.08.11 |
---|---|
REST API & HTTP Requests (0) | 2021.08.11 |
Working with Ajax & JSON (0) | 2021.08.10 |
XHR Object Methods & Working With Text File (0) | 2021.08.10 |
★Ajax & XHR introduction (0) | 2021.08.10 |