Before the Fetch API, the traditional way to make AJAX requests was using XMLHttpRequest
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX with XMLHttpRequest</title>
</head>
<body>
<button id="fetchDataBtn">Fetch Data</button>
<div id="dataOutput"></div>
<script>
document.getElementById('fetchDataBtn').addEventListener('click', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
xhr.onload = function() {
if (this.status === 200) {
var data = JSON.parse(this.responseText);
document.getElementById('dataOutput').innerHTML = `
<h3>${data.title}</h3>
<p>${data.body}</p>
`;
}
};
xhr.onerror = function() {
console.error('Request failed.');
};
xhr.send();
});
</script>
</body>
</html>