如何将json文本转换为html DOM

时间:2015-05-21 05:55:11

标签: javascript json

我能够从外部URL JSON获取数据,但是不能将它放入DOM中,不能确定我做错了什么,但这是我的代码。我怀疑它与obj.fruit.json有关但不太确定

<!DOCTYPE html>
<html>
  <head>
    <title>Starting Point</title>
    <script>
      function do_exercise()
      {
        var x = new XMLHttpRequest();
        x.open('GET', 'http://tmaserv.scem.uws.edu.au/fruit.json', true);
            x.onreadystatechange = function() {
        if (x.readyState == 4 && x.status ==200) {
            alert(x.responseText);
            obj = JSON.parse(text);
            document.getElementById("section1").innerHTML =
            obj.fruit.json[2].name + " " + 
            obj.fruit.json[2].description;
        }
      }
        x.send(null);
      }
    </script>
  </head>
  <body>
    <nav>           
      <button onclick="do_exercise();">Click Me</button>        
    </nav>
    <section id = "section1">
      <h1>Heading One</h1>
      <p>Paragraph One.</p>
    </section>
  </body>
</html>

欢呼声

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE html>
<html>
<head>
  <title>Starting Point</title>
  <script>
    function do_exercise () {
        var x = new XMLHttpRequest();
        x.open('GET', 'http://tmaserv.scem.uws.edu.au/fruit.json', true);
        x.onreadystatechange = function() {
            if (x.readyState == 4 && x.status ==200) {
                obj = JSON.parse(x.responseText);
                document.getElementById("section1").innerHTML =
                obj[2].name + " " + 
                obj[2].description;
            }
        }

        x.send(null);
    }
  </script>
</head>
<body>
    <nav>           
      <button onclick="do_exercise();">Click Me</button>      
    </nav>
    <section id = "section1">
      <h1>Heading One</h1>
      <p>Paragraph One.</p>
    </section>
</body>
</html>