Skip to content

Instantly share code, notes, and snippets.

@includeamin
Created May 6, 2019 10:16
Show Gist options
  • Save includeamin/a765c31a055a9ff98e1e60fb7c308c4d to your computer and use it in GitHub Desktop.
Save includeamin/a765c31a055a9ff98e1e60fb7c308c4d to your computer and use it in GitHub Desktop.
fill table with json in html
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable" border="1" style="width: 100%">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
//first add an event listener for page load
document.addEventListener( "DOMContentLoaded", get_json_data, false ); // get_json_data is the function name that will fire on page load
//this function is in the event listener and will execute on page load
function get_json_data(){
// Relative URL of external json file
var json_url = 'http://chichiapp.ir:3050/Product/get';
//Build the XMLHttpRequest (aka AJAX Request)
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {//when a good response is given do this
var data = JSON.parse(this.responseText); // convert the response to a json object
console.log(data.Description)
append_json(data.Description);// pass the json object to the append_json function
}
}
//set the request destination and type
xmlhttp.open("GET", json_url, true);
//set required headers for the request
//xmlhttp.setRequestHeader("Content-type", "multipart/data-form");
// send the request
xmlhttp.send(); // when the request completes it will execute the code in onreadystatechange section
}
//this function appends the json data to the table 'gable'
function append_json(data){
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.Name + '</td>' +
'<td>' + object.Manufacture + '</td>' +
'<td>' + object.Count + '</td>' +
'<td>' + object.Cost + '</td>';
table.appendChild(tr);
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment