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>