onlyforbopi
9/27/2018 - 7:18 AM

JS.JSON.FetchingDatawithXHR.v2

JS.JSON.FetchingDatawithXHR.v2

table,tr, td {
    border-collapse:collapse;
    border:1px solid grey;
}
td {
    padding-left: 5px;
    padding-right:5px;
}
tr:hover{
    background-color: #f0eeee;
}

function importData() {
    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 has arrived
    xhr.onload = function(e) {
        var jsonResponse = this.response;
        // turn the response into a JavaScript object
        var users = JSON.parse(jsonResponse);
        displayUsersAsATable(users);
    }

    // in case of error
    xhr.onerror = function(err) {
        console.log("Error: " + err);
    }

    // sends the request
    xhr.send();
}

function displayUsersAsATable(userList)
{
    var table = document.getElementById("generated");
    userList.data.forEach(function (item) {

        let tableRrow = table.insertRow();
        item.forEach(function (cell) {
            let tableCell = tableRrow.insertCell();
            tableCell.innerHTML = cell;
        })
    });
}
<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <link href="StyleSheet.css" rel="stylesheet" />
    <script src="JavaScript.js"></script>
</head>
<body>
    <button onclick="importData()">Press to Import data</button>
    <table id="generated"></table>
</body>
</html>