html JS.JSON.FetchingData.PopulateTable.ex9

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html JS.JSON.FetchingData.PopulateTable.ex9相关的知识,希望对你有一定的参考价值。

table {
  margin-top: 20px;
}
table, tr, td {
  border: 1px solid;
} 

tr:nth-child(even) {
  background: khaki;
}


  function search() {    
    var queryURL = "https://gist.githubusercontent.com/heiswayi/7fde241975ed8a80535a/raw/ff1caaeaf62bd6740ab7cafcd61f1215de173379/datatables-data.json";
    
    var xhr = new XMLHttpRequest();
    xhr.open('GET', queryURL, true);

    // called when the response is arrived
    xhr.onload = function(e) {
      var jsonResponse = xhr.response;
      
      // turn the response into a JavaScript object
      var employees = JSON.parse(jsonResponse);
      //alert("employees length: " + employees['data'].length + ", first is " + employees['data'][0]);
      
      displayUsersAsATable(employees);
    }
    
    // in case of error
    xhr.onerror = function(err) {
      console.log("Error: " + err);
    }
    
    // sends the request
    xhr.send();
} 
  
function displayUsersAsATable(employees) {
    // employees is a JavaScript object
  
    // empty the div that contains the results
    var employeesDiv = document.querySelector("#employees");
    employeesDiv.innerHTML = "";
  
    // creates and populate the table with employees
    var table = document.createElement("table");
    
    employeeData = employees['data'];
    // iterate on the array of users
    employeeData.forEach(function(currentEmployee) {
        // creates a row
        //alert('currentEmployee: ' + currentEmployee);
        var row = table.insertRow();
      
        currentEmployee.forEach(function(data){
          // insert cells in the row
          var cell = row.insertCell();
          cell.innerHTML = data;
        });
     });
  
     // adds the table to the div
     employeesDiv.appendChild(table);
}
JS.JSON.FetchingData.PopulateTable.ex9
--------------------------------------


A [Pen](https://codepen.io/Onlyforbopi/pen/LgYJmv) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).

[License](https://codepen.io/Onlyforbopi/pen/LgYJmv/license).
<html lang="en">
<head>
<title>Working with remote data using XhR2</title>
  <meta charset="utf-8"/>
</head>
<body>
  <p>Working with remote data suing XhR2</p>
  <button onclick="search();">Get a remote list of employess and their details</button>
  <div id="employees"></div>
</body>
</html>

以上是关于html JS.JSON.FetchingData.PopulateTable.ex9的主要内容,如果未能解决你的问题,请参考以下文章

html JS.JSON.FetchingData.PopulateTable.ex4

html JS.JSON.FetchingData.PopulateTable.ex9

html JS.JSON.FetchingData.PopulateTable.ex8

html JS.JSON.FetchingData.PopulateTable.ex7

html JS.JSON.FetchingData.PopulateTable.ex6

html JS.JSON.FetchingData.PopulateTable.ex5