Program10

 <!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>AJAX and JSON Example</title>

<style>

body {

font-family: Arial, sans-serif;

margin: 20px;

text-align: center;

}

.content {

margin: 20px auto;

padding: 20px;

border: 1px solid #ddd;

width: 300px;

text-align: left;

}

button {

padding: 10px 15px;

margin: 10px 5px;

cursor: pointer;

background-color: #4caf50;

color: white;

border: none;

border-radius: 5px;

}

button:hover {

background-color: #388e3c;

}

h1 {

margin-bottom: 30px;

}

</style>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body>

<h1>AJAX and JSON Demonstration</h1>

<!-- Content sections -->

<div id="content-js" class="content">Content will load here (Vanilla

JS).</div>

<div id="content-jquery" class="content">Content will load here (jQuery

AJAX).</div>

<div id="json-content" class="content">JSON content will load here

(getJSON).</div>

<div id="parsed-json" class="content">Parsed JSON will display here

(parseJSON).</div>

<!-- Buttons -->

<button id="load-text-js">Load Text (Vanilla JS)</button>

<button id="load-text-jquery">Load Text (jQuery AJAX)</button>

<button id="load-json">Load JSON (getJSON)</button>

<button id="parse-json-btn">Parse JSON</button>

<script>

document.addEventListener("DOMContentLoaded", function() {

// a. AJAX using Vanilla JavaScript

document.getElementById("load-text-js").addEventListener("click",

function() {

const xhr = new XMLHttpRequest();

xhr.open("GET", "example.txt", true);

xhr.onload = function() {

if (this.status === 200) {

document.getElementById("content-js").innerText =

this.responseText;

}

};

xhr.send();

});

// b. AJAX using jQuery

$("#load-text-jquery").click(function() {

$.ajax({

url: "example.txt",

method: "GET",

success: function(data) {

$("#content-jquery").text(data);

}

});

});

// c. Using getJSON method

$("#load-json").click(function() {

$.getJSON("data.json", function(data) {

let output = "<ul>";

$.each(data, function(key, value) {

output += `<li>${key}: ${value}</li>`;

});

output += "</ul>";

$("#json-content").html(output);

});

});

// d. Using parseJSON method

$("#parse-json-btn").click(function() {

const jsonString = '{"name": "John Doe", "age": 30, "city":

"New York"}';

const parsedData = $.parseJSON(jsonString);

$("#parsed-json").html(

`<p>Name: ${parsedData.name}</p>

<p>Age: ${parsedData.age}</p>

<p>City: ${parsedData.city}</p>`

);

});

});

</script>

</body>

</html>

Comments

Popular posts from this blog

Plantation

Program9

Program8