简体   繁体   中英

How to automatically update JSON data without page refresh using php or javascript?

I have a google sheet where stock data is being updated every 3 minutes. I have a page where I can see the data in html table. but that data is not changing automatically. I have to refresh the page or I have to set meta <meta http-equiv="refresh" content="30"> to refresh the page periodically.

I want the data coming from JSON must have to be updated automatically without the page refresh. here is my code.

JSON Object Link

https://docs.google.com/spreadsheets/d/xxxxxxxxxx.json

Div to show json data

<div id="json">json here</div>

Javascript to fetch and show json data

<script type="text/javascript">
var id = 'xxxxxxxxxxxxxxxxxxxx';
var gid = '0';
var url = 'https://docs.google.com/spreadsheets/d/'+id+'/gviz/tq?tqx=out:json&tq&gid='+gid;
fetch(url)
  .then(response => response.text())
  .then(data => document.getElementById("json").innerHTML=myItems(data.substring(47).slice(0, -2))  
  );
function myItems(jsonString){
  var json = JSON.parse(jsonString);
  var table = '<table><tr>'
  json.table.cols.forEach(colonne => table += '<th>' + colonne.label + '</th>')
  table += '</tr>'
  json.table.rows.forEach(ligne => {
    table += '<tr>'
    ligne.c.forEach(cellule => {
        try{var valeur = cellule.f ? cellule.f : cellule.v}
        catch(e){var valeur = ''}
        table += '<td>' + valeur + '</td>'
      }
    )
    table += '</tr>'
    }
  )
  table += '</table>'
  return table
}
</script>

I know one js library kickout js, but i am unable to implement and get desired result using kickout js. so how I can achieve a table which updates JSON data automatically without page refresh ?

Thank you in advance.

You have to fetch new data periodically using setInterval and update your table rows. You can assign a unique ID to each row and update them in your function that runs periodically.

setInterval(function() {
    // fetch data here and update rows.
}, 180000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM