onlyforbopi
9/27/2018 - 7:17 AM

JS.JSON.Downloading project JSON data using the Xhr2 API

JS.JSON.Downloading project JSON data using the Xhr2 API

p {
  border:1px solid blue;
  padding:10px;
  background-color:lightgray;
}

button {
  border:1px solid green;
  padding:7px;
  background-color:yellow;
}

table {
  border:1px solid;
  margin-top:20px;
}
tr,td,td {
  border:1px solid;
  background-color:lightblue;
  padding:10px;
}
function search() {
  var queryURL = "https://gist.githubusercontent.com/heiswayi/7fde241975ed8a80535a/raw/ff1caaeaf62bd6740ab7cafcd61f1215de173379/datatables-data.json";
  var xhr = new XMLHttpRequest();
  xhr.open('GET', queryURL, true);
  
  xhr.onload = function(e) {
    var jsonResponse = xhr.response;
    
    var users = JSON.parse(jsonResponse);
    displayUsersAsATable(users);
  }
  
  xhr.onerror = function(err) {
    console.log("Error: " +err);
  }
  
  xhr.send();
}

function displayUsersAsATable(users){
  var usersDiv = document.querySelector("#users");
  usersDiv.innerHTML = "";
  
  var table = document.createElement("table");
  var usersData = users['data'];
  usersData.forEach(function(currentUser) {
    var row = table.insertRow();
    currentUser.forEach(function(data){
      var cell = row.insertCell();
      cell.innerHTML = data;
    })
  });
  
  usersDiv.appendChild(table);
  
}

JS.JSON.Downloading project JSON data using the Xhr2 API

A Pen by Pan Doul on CodePen.

License.

<p>Working with remote data using XhR2</p>
<button onclick="search();">Get Data</button>
<div id="users"></div>