getJSON返回undefined

时间:2014-08-31 04:39:11

标签: javascript jquery html json

我正在尝试在项目网站上创建一个自动新闻源,其中所有帖子都放入JSON文件,然后相应地在新闻页面上格式化。我终于想出了如何让json解析器显示SOMETHING,但是整个页面上只有一些“未定义”的位。我做错了什么?

jquery / html片段

<script>    
    $.getJSON("js/news.json", function (data) {
        $.each(data.posts, function (val) {
                var title = val.title;
                var date = val.date;
                var content = val.content;
                $("#newscontainer").append('<div><h1>' + title + '</h1><h2>' + date +     '</h2><p>' + content + '</p></div>');
        });
    });
</script>
<div id='newscontainer'> 
</div>

JSON片段

{
"posts": [
    {
        "title": "title1",
        "date": "8302014",
        "content": "LotsoftextLotsoftext"
    },
    {
        "title": "title2",
        "date": "8312014",
        "content": "CopiousquantitiesoftextCopiousquantitiesoftext"
    },
    {
        "title": "title3",
        "date": "8322014",
        "content": "onlyalittletext"
    }
]
}

3 个答案:

答案 0 :(得分:2)

代码中的

valindex,您应该使用回调的第二个参数。

$.each(data.posts, function (index, val) {

您还可以使用this关键字。

答案 1 :(得分:-1)

试试这个:

var post_title = val.title;
var post_date = val.date;
var post_content = val.content;

var divTag   = document.createElement("div");
newscontainer.appendChild(divTag); 

var h1Tag   = document.createElement("h1");
h1Tag.innerHTML = post_title;
newscontainer.appendChild(h1); 

var h2Tag   = document.createElement("h2");
h2Tag.innerHTML = post_date;
newscontainer.appendChild(h2); 

var pTag   = document.createElement("p");
pTag.innerHTML = post_content;
newscontainer.appendChild(p); 

答案 2 :(得分:-1)

您可以使用列表中的each()函数:

    $(data.posts).each(function() {
      var $this = this;
      $("#newscontainer").append('<div><h1>' + $this.title + '</h1><h2>' + $this.date +     '</h2><p>' + $this.content + '</p></div>');
    });
相关问题