简体   繁体   中英

Using Jquery, how do you update elements in an html page based on the key names returned in a JSON document?

I am currently asynchronously fetching json documents to update elements in a few html pages. My current approach seems less that elegant. For many pages I just need to update an element on the HTML page that corresponds to a key in the being returned in the json document. I'm looking for a simple jquery/javascript function that updates text boxes and other simple elements whenever an html element name in the fetching page matches a key returned in the json document.

The ideal function would fetch the json document when the html page first loads and then fetch the json document again every minute after that. The idea is to be able to update additional html elements just by adding additional name/value pairs in returned json document.

The following should do the trick. Assuming, I understood what you were requesting.


function updateElements() {
 function handleJSON(data) {
   for (key in data) {
     if ( ! data.hasOwnProperty(key)) {
       continue;
     }
     $('#'+key).html(data[key]);
   }
 };
 $.ajax({
  url: your_url,
  dataType: 'json',
  data: data,
  success: handleJSON
 });
};
setInterval(updateElements, 60000);

Assuming jdata contains the JSON data, the following will replace document elements whose ids correspond to the jdata keys.

  var k, kel;
  for (k in jdata) {
    if (jdata.hasOwnProperty (k) && (kel = document.getElementById (k))) {
       k.innerHTML = jdata[k];
    }
  } 

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