views:

62

answers:

2

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.

A: 

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];
    }
  } 
Hans B PUFAL
+1  A: 
ocdcoder
I tried this but it didn't quite work. I had to add the # in front of the key. Then it seems to work.$(key).html(data[key]); -> $("#"+key).html(json[key]);
Chris
oh, yea, missed that. glad its workin for ya now though!
ocdcoder
Can you add the change to your answer so that the next interested person can use it?
Chris
good idea, edited!
ocdcoder