Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing XML

XML AJAX Files:



XML and AJAX files work together in a simple example:

1. XML File:

Suppose you have an XML file named data.xml containing some data:

        

Example

<?xml version="1.0" encoding="UTF-8"?> <books> <book> <title>The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <year>1925</year> </book> <book> <title>The Catcher in the Rye</title> <author>J.D. Salinger</author> <year>1951</year> </book> </books>

2. HTML File:

Create an HTML file named index.html that includes a button to trigger the AJAX request and a placeholder to display the fetched data:

        

Example

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX Example</title> <script src="script.js" defer></script> </head> <body> <h2>Fetch Data Using AJAX</h2> <button id="fetchButton">Fetch Data</button> <div id="output"></div> </body> </html>

3. JavaScript (AJAX) File:

Create a JavaScript file named script.js to handle the AJAX request and update the HTML content with the fetched XML data:

            

Example

document.getElementById('fetchButton').addEventListener('click', fetchData); function fetchData() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var xmlDoc = this.responseXML; displayData(xmlDoc); } }; xhttp.open('GET', 'data.xml', true); xhttp.send(); } function displayData(xmlDoc) { var outputDiv = document.getElementById('output'); outputDiv.innerHTML = ''; var books = xmlDoc.getElementsByTagName('book'); for (var i = 0; i < books.length; i++) { var title = books[i].getElementsByTagName('title')[0].textContent; var author = books[i].getElementsByTagName('author')[0].textContent; var year = books[i].getElementsByTagName('year')[0].textContent; var bookInfo = '<p>Title: ' + title + '</p>'; bookInfo += '<p>Author: ' + author + '</p>'; bookInfo += '<p>Year: ' + year + '</p>'; bookInfo += '<hr>'; outputDiv.innerHTML += bookInfo; } }

Explanation:

This example demonstrates how to use AJAX to fetch XML data from a server and display it dynamically on a web page.




Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java