2014-08-31 295 views
1

我想在项目网站上做一个自动新闻提要,其中所有的帖子都放入一个JSON文件,然后相应地在新闻页面上格式化。我终于想出了如何让json解析器显示SOMETHING,但是在页面上的东西只是一堆“未定义”的位。我究竟做错了什么?getJSON返回undefined

了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" 
    } 
] 
} 

回答

2

val在你的代码是index,你应该使用回调的第二个参数。

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

您还可以使用this关键字。

+1

添加一个小词固定的一切!非常感谢。我明白为什么它也起作用......情况并非总是如此。几个月前我刚刚开始编码。 – Jeremy 2014-08-31 05:06:03

-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); 
-1

您可以使用每个()函数在您的名单:

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