如何将json数据放在HTML中

时间:2011-05-19 07:43:31

标签: ajax

喜 我想知道如何将json数据放入html 是否有标签或什么,它是否放在身体下?

`["book":

        {
        "title":"JavaScript, the Definitive Guide",
        "publisher":"O'Reilly",
        "author":"David Flanagan",
        "cover":"/images/cover_defguide.jpg",
        "blurb":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
            },


        {
        "title":"DOM Scripting",
        "publisher":"Friends of Ed",
        "author":"Jeremy Keith",
        "cover":"/images/cover_domscripting.jpg",
        "blurb":"Praesent et diam a ligula facilisis venenatis."
            },

        {
        "title":"DHTML Utopia: Modern Web Design using JavaScript & DOM",
        "publisher":"Sitepoint",
        "author":"Stuart Langridge",
        "cover":"/images/cover_utopia.jpg",
        "blurb":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit."

    }
]`
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5

  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {

    var addrField = document.getElementById('myDiv');

    var card = eval('(' + xmlhttp.responseText + ')');
    addrField.value = card.places.place.name.value;
    }
  };

xmlhttp.open("GET","HTMLPage3.htm",true);
xmlhttp.send();

1 个答案:

答案 0 :(得分:2)

你拥有的是无效的JSON。 book属性未正确定义。您可以使用<script>标记将其存储在HTML文档中,并确保已修复此JSON,否则可能会出现javascript错误:

<script type="text/javascript">
var books = [
    {
        "title":"JavaScript, the Definitive Guide",
        "publisher":"O'Reilly",
        "author":"David Flanagan",
        "cover":"/images/cover_defguide.jpg",
        "blurb":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
    },
    {
        "title":"DOM Scripting",
        "publisher":"Friends of Ed",
        "author":"Jeremy Keith",
        "cover":"/images/cover_domscripting.jpg",
        "blurb":"Praesent et diam a ligula facilisis venenatis."
    },
    {
        "title":"DHTML Utopia: Modern Web Design using JavaScript & DOM",
        "publisher":"Sitepoint",
        "author":"Stuart Langridge",
        "cover":"/images/cover_utopia.jpg",
        "blurb":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
    }
];
</script>

现在你可以遍历这个数组的元素了:

for (var i = 0; i < books.length; i++) {
    var book = books[i];
    alert(book.title);
}