Week 10&11

Task 3
 avatar
user_1373341
html
8 months ago
2.7 kB
1
Indexable
Never
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Task 3</title>
  </head>
  <body>
    <button onclick="makeAjaxQuery()">Search Airport</button>
    <br/>
    <br/>
    <div id="display"></div>

    <script type="text/javascript">
      function makeAjaxQuery() {
        // create an XMLHttpRequest
        var xhttp = new XMLHttpRequest();
        // create a handler for the readyState change
        xhttp.onreadystatechange = function() {
          readyStateChangeHandler(xhttp);
        };
        // get JSON file by making async call
        xhttp.open("GET", "airport.json", true);
        xhttp.send();
      }

      // handler for the readyState change
      function readyStateChangeHandler(xhttp) {
        if (xhttp.readyState == 4) {
          // readyState = 4 means DONE
          if (xhttp.status == 200) {
            // status = 200 means OK
            handleStatusSuccess(xhttp);
          } else {
            // status is NOT OK
            handleStatusFailure(xhttp);
          }
        }
      }

      // XMLHttpRequest failed
      function handleStatusFailure(xhttp) {
        // display error message
        var display = document.getElementById("display");
        display.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
      }

      // XMLHttpRequest success
      function handleStatusSuccess(xhttp) {
        var jsonText = xhttp.responseText;
        // parse the json into an object
        var airportObj = JSON.parse(jsonText);
        // display the object on the page
        displayAirport(airportObj);
      }

      function displayAirport(airportObj) {
      	// show the constructed HTML code in the display div
        var display = document.getElementById("display");

        // construct HTML code to display weather information
        console.log(airportObj);
        var html = "";
        html += "<b>Search Query: </b>" + airportObj.searchQuery + "<br/><br/>";
        html += "<table border='1'>";
        html += "<tr><th>Airport</th><th>ICAO</th><th>IATA</th><th>Location</th></tr>";

        for(var i=0; i < airportObj.searchResult.length; i++){
          var searchObj = airportObj.searchResult[i];

          html += "<tr>";
          html += "<td>" + searchObj.airportName + "</td>";
          html += "<td>" + searchObj.ICAO + "</td>";
          html += "<td>" + searchObj.IATA + "</td>";
          html += "<td>" + searchObj.city + ", " + searchObj.country + "</td>";
          html += "</tr>";
        }

        display.innerHTML = html;
      }
    </script>
  </body>
</html>