AJAX สามารถใช้สำหรับการสื่อสารเชิงโต้ตอบกับไฟล์ XML
ตัวอย่างต่อไปนี้จะแสดงให้เห็นว่าหน้าเว็บสามารถดึงข้อมูลได้อย่างไร จากไฟล์ XML ด้วย AJAX:
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
myFunction(this);
}
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
}
function myFunction(xml) {
const xmlDoc = xml.responseXML;
const x = xmlDoc.getElementsByTagName("CD");
let table="<tr><th>Artist</th><th>Title</th></tr>";
for (let i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
เมื่อผู้ใช้คลิกที่ปุ่ม "รับข้อมูลซีดี" ด้านบน loadDoc()
ฟังก์ชันถูกดำเนินการ
ฟังก์ชัน loadDoc()
สร้างวัตถุ XMLHttpRequest
เพิ่มฟังก์ชัน จะดำเนินการเมื่อการตอบสนองของเซิร์ฟเวอร์พร้อม และส่งคำขอไปยังเซิร์ฟเวอร์
เมื่อการตอบสนองของเซิร์ฟเวอร์พร้อม HTML ตารางถูกสร้างขึ้น โหนด (องค์ประกอบ) จะถูกแยกออกจากไฟล์ XML และในที่สุดก็จะอัปเดต องค์ประกอบ "สาธิต" ด้วยตาราง HTML ที่เต็มไปด้วยข้อมูล XML:
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {myFunction(this);}
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
}
function myFunction(xml) {
const xmlDoc = xml.responseXML;
const x = xmlDoc.getElementsByTagName("CD");
let table="<tr><th>Artist</th><th>Title</th></tr>";
for (let i = 0; i <x.length;
i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue
+
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue
+
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
ไฟล์ XML ที่ใช้ในตัวอย่างด้านบนมีลักษณะดังนี้: "https://basicit.org/js/cd_catalog.xml"