-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
42 lines (34 loc) · 1.38 KB
/
Copy pathscript.js
File metadata and controls
42 lines (34 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
document.getElementById('fetchCat').addEventListener('click', function() {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure it: GET-request for the cat image API
xhr.open('GET', 'https://rory.cat/purr', true);
// Set up a function to handle the response
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
// Parse the JSON response
var data = JSON.parse(xhr.responseText);
// Clear previous output
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
// Create an image element
var img = document.createElement('img');
img.src = data.url; // The URL of the cat image
img.alt = 'Cute Cat'; // Alt text for the image
// Create a title element
var title = document.createElement('p');
title.textContent = `Cat ID: ${data.id}`; // Display the cat ID
// Append the image and title to the output div
outputDiv.appendChild(img);
outputDiv.appendChild(title);
} else {
console.error('Request failed with status:', xhr.status);
}
};
// Handle network errors
xhr.onerror = function() {
console.error('Request failed');
};
// Send the request
xhr.send();
});