XML AJAX

XML and AJAX are commonly used together to facilitate asynchronous data exchange between a client and a server. Here’s a breakdown:

XML (Extensible Markup Language)

  • A markup language used to store and transport data.
  • Data is structured in a hierarchical format using tags.
  • Often used in web services and configurations.

AJAX (Asynchronous JavaScript and XML)

  • A technique that allows web pages to update asynchronously by exchanging data with a web server behind the scenes.
  • Prevents full-page reloads, improving user experience.
  • Although AJAX originally used XML, JSON is now more commonly used due to its lightweight nature.

Using AJAX with XML

AJAX can retrieve XML data from a server and update the webpage dynamically. Here’s a basic example:

Example: Fetching XML using AJAX

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX with XML</title>
    <script>
        function loadXML() {
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    let xmlDoc = this.responseXML;
                    let items = xmlDoc.getElementsByTagName("item");
                    let output = "<ul>";
                    for (let i = 0; i < items.length; i++) {
                        output += "<li>" + items[i].textContent + "</li>";
                    }
                    output += "</ul>";
                    document.getElementById("result").innerHTML = output;
                }
            };
            xhr.open("GET", "data.xml", true);
            xhr.send();
        }
    </script>
</head>
<body>

    <button onclick="loadXML()">Load XML Data</button>
    <div id="result"></div>

</body>
</html>

Example XML File (data.xml)

<?xml version="1.0" encoding="UTF-8"?>
<items>
    <item>Item 1</item>
    <item>Item 2</item>
    <item>Item 3</item>
</items>

How It Works

  1. The loadXML() function creates an XMLHttpRequest object.
  2. It sends a request to fetch data.xml from the server.
  3. When the request is successful, it parses the XML response.
  4. The data is dynamically inserted into the HTML page.

Would you like an example using fetch() instead of XMLHttpRequest?

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment