📚 The loadDoc() Function: AJAX Implementations
1. Basic loadDoc() Function (Original)
The classic implementation using XMLHttpRequest
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Click button to load content here
3. Modern loadDoc() with Fetch API
Using modern JavaScript Fetch API with async/await
async function loadDocModern(url, elementId, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await (options.json ? response.json() : response.text());
document.getElementById(elementId).innerHTML = formatData(data, options.json);
return data;
} catch (error) {
document.getElementById(elementId).innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
throw error;
}
}
Modern Fetch API results will appear here
4. Complete AJAX Utility Library
A comprehensive loadDoc() implementation with all features
class AjaxLoader {
constructor(baseURL = '') {
this.baseURL = baseURL;
this.requests = {};
}
loadDoc(url, options = {}) {
const config = {
method: options.method || 'GET',
headers: options.headers || {},
body: options.body,
timeout: options.timeout || 30000,
responseType: options.responseType || 'text',
onProgress: options.onProgress,
onSuccess: options.onSuccess,
onError: options.onError
};
}
}
AJAX Library test results