var url='https://gist.githubusercontent.com/heiswayi/7fde241975ed8a80535a/raw/ff1caaeaf62bd6740ab7cafcd61f1215de173379/datatables-data.json';
var buttonXHR,buttonFetch , div ;
var table;
window.onload=init;
function init()
{
buttonXHR=document.querySelector('#buttonXHR') ;
buttonFetch=document.querySelector('#buttonFetch') ;
div=document.querySelector('#container') ;
}
function getDataXHR()
{
var xhr=new XMLHttpRequest() ;
xhr.open('GET',url,true) ;
xhr.onload=function(e)
{
var response=this.response ;
var obj=JSON.parse(response) ;
createTable(obj,'created using XHR class');
};
xhr.onerror=function(error)
{
console.log('Error '+ error) ;
}
xhr.send();
}
function getDataFetch()
{
fetch(url)
.then(function(response)
{
return response.json();
})
.then(function(data)
{
createTable(data,'created using Fetch API');
})
.catch(function(error)
{
console.log('Error :'+ error.message);
})
}
function createTable(obj,method)
{
removeTable();
table= document.createElement('table') ;
table.classList.add('table');
var caption=table.createCaption() ;
caption.innerHTML=method;
var len=obj.data.length ;
for(var i=0;i<len;i++)
{
var row=table.insertRow() ;
var cells=obj.data[i].length;
for(var x=0;x<cells;x++)
{
var cell=row.insertCell() ;
var txt=obj.data[i][x];
cell.innerHTML=txt;
}
}
div.appendChild(table) ;
}
function removeTable()
{
if(table!==undefined)
{
div.removeChild(table);
}
}
JS.JSON.FetchingData.XHR.Fetch.ex1
----------------------------------
A [Pen](https://codepen.io/Onlyforbopi/pen/GYKmJv) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).
[License](https://codepen.io/Onlyforbopi/pen/GYKmJv/license).