You are on page 1of 5

SAKSHI SHARMA

21/5005
PRACTICAL-7
Store JSON data of few pets that you
created in previous practical in a JSON
file (copy from console output of previous
program to a .json file). Using AJAX, load
data from the file and display it in a
presentable way using HTML and CSS.

Code for the following question:-

HTML
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<link rel="stylesheet" href="styles.css">

<title>Pets Information</title>

</head>

<body>

<div id="pets-container"></div>

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

</body>

</html>

CSS
#pets-container {

max-width: 600px;

margin: 20px auto;

.pet {

border: 1px solid #ccc;

padding: 10px;

margin-bottom: 10px;

border-radius: 5px;

.pet h2 {

margin-top: 0;

.pet p {

margin-bottom: 5px;

JAVASCRIPT
$(document).ready(function() {

$.ajax({

url: 'pets.json',

type: 'GET',

dataType: 'json',

success: function(data) {

displayPets(data);

},

error: function() {

console.log('Error loading JSON file');

});

function displayPets(pets) {

var petsContainer = $('#pets-container');

pets.forEach(function(pet) {

var petDiv = $('<div class="pet">');

petDiv.append('<h2>' + pet.name + '</h2>');

petDiv.append('<p>Species: ' + pet.species + '</p>');

petDiv.append('<p>Age: ' + pet.age + ' years</p>');

petsContainer.append(petDiv);

});

});
A.

You might also like