How we can get JSON data using AJAX?

Asked 19-Aug-2021
Viewed 649 times

1 Answer


1

student.json

[

  {
    'ID': '1',
    'Name': 'Senpai',
    'Gender': '1',
    'Class': '32',
    'Seat': '15'
  },
  {
    'ID': '2',
    'Name': 'Yui Rio',
    'Gender': '0',
    'Class': '11',
    'Seat': '14'
  },
  {
    'ID': '3',
    'Name': 'Yuna Hina',
    'Gender': '0',
    'Class': '12',
    'Seat': '14'
  },
  {
    'ID': '4',
    'Name': 'Koharu Hinata',
    'Gender': '0',
    'Class': '21',
    'Seat': '14'
  },
  {
    'ID': '5',
    'Name': 'Mei Mio',
    'Gender': '0',
    'Class': '22',
    'Seat': '14'
  }
]

Example.html

<html>  

<head>
    <meta content='text/html; charset=utf-8'>
    <title>AJAX JSON by Javatpoint</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC' crossorigin='anonymous'>
</head>
<body>
    <div class='container mt-3'>
        <h1 class='text-center'>fatch data from json file</h1>
        <button type='button' class='btn btn-primary' onclick='loadJSONData()'>Load JSON Information</button>
        <h2 class='mt-2 text-center text-danger' id='dummy'>Student table here</h2>
        <table id='loadDataInTable' class='mt-1 table table-striped table-hover'>
        </table>
        <p></p>
    </div>
<script >
    function loadJSONData() {
        var request;
        if (window.XMLHttpRequest) {
            request = new XMLHttpRequest();//for Chrome, mozilla etc
        }
        request.onreadystatechange = function () {
          if (request.readyState == 4) {
              var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object
              let table = '<thead class=\'thead-dark\'><tr><th> # </th><th>Name</th><th>Gender</th><th>Class</th><th>Seat</th></tr></thead>';
              jsonObj.forEach(element => {
                  table += '<tr><td> ' + element.ID + ' </td>'
                      + '<td> ' + element.Name + ' </td>'
                      + '<td> ' + element.Gender + ' </td>'
                      + '<td> ' + element.Class + ' </td>'
                      + '<td> ' + element.Seat + ' </td></tr> ';
              });
              document.getElementById('dummy').remove();
              document.getElementById('loadDataInTable').innerHTML = table;
            }
        }
        request.open('GET', 'student.json', true);
        request.send();
    }
</script>
</body>
</html>  

Output

How we can get JSON data using AJAX?

How we can get JSON data using AJAX?