简体   繁体   中英

Display JSON arrays in innerHTML

so I received the following array from another student and my job is to display it in the HTML.

I've followed examples found on here as well as other sites. It's my first attempt at doing this.

Anyway, I've called in the required values, but they're not displaying. I'd appreciate any help I can get.

This is the script block and I'll attach some of the HTML. Currently the json is situated before the closing head tag.

 <script>

      var height = {"height" : "1.76m"};
      var weight = {"weight" : "65kg"};
      var bmi = {weight/(height*height)};
      var cholesterol = {"cholesterol" : "26mmol/d"};
      var glucose ={"glucose" : "100mg/dl"};
      var pressure = {"pressure" : "120/80"};
      var pulseRate = {"pulse rate" : "80bpm"};

      window.onload = function() {

        obj = JSON.parse(height, weight, bmi, cholesterol, glucose, pressure, pulseRate);

        document.getElementById("hgt").innerHTML = obj.height[1];
        document.getElementById("wgt").innerHTML = obj.weight[1];
        document.getElementById("bmi").innerHTML = obj.bmi[1];
        document.getElementById("chol").innerHTML = obj.cholesterol[1];
        document.getElementById("gluc").innerHTML = obj.glucose[1];
        document.getElementById("bp").innerHTML = obj.pressure[1];
        document.getElementById("rpr").innerHTML = obj.pulseRate[1];

      };

 </script>

      <div class="col-xs-2">
        <h3 class="heading">Today</h3>
        <img class="picture2" src="images/icon-height.png" />
      <div class="caption">
       <h2 id="hgt"></h2>
       <p>height</p>
      </div>

Since your variables height , weight ... do not have to be parsed, since they are valid JSON Objects, you could save yourself some time by assigning obj like this:

var obj = {
   height: "1.76",
   weight: "65kg",
   ...,
   bmi: //your calculation here!
};

document.getElementById("yourid").innerHTML = obj.weight;
...

Since JSON objects use key : value pairs, you can simply access the values by using object.key or object['key'] .

Since you're trying to access the values by using obj.weight[1] I'm guessing that you're trying to get the second value in { "weight" : "67kg" } . But since this is a valid Object, weight is the key and "67kg" is the value. So you are trying to get the value at index 1 on an Object ( obj.weight[1] ). For this to work your object must have a key 1 or be an array. I hope you get what I'm trying to explain to you.

To make it a lot more simpler, you could just use height.height instead of the not working obj.height[1] , because your var height is an object with a key height . But for readability I would suggest the format from my snippet.

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