简体   繁体   English

getJSON返回未定义

[英]getJSON returning undefined

I'm trying to make an automatic news feed on a project website, where all the posts are put into a JSON file and then formatted on the news page accordingly. 我正在尝试在项目网站上创建自动新闻提要,其中所有帖子都放入JSON文件中,然后相应地在新闻页面上进行格式化。 I've finally figured out how to get the json parser to show SOMETHING but that something is just a bunch of "undefined" bits all over the page. 我终于弄清楚了如何让json解析器显示某些内容,但整个页面上只是一堆“未定义”的位。 What am I doing wrong? 我究竟做错了什么?

The jquery/html snippet 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>

The JSON snippet JSON代码段

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

val in your code is the index , you should use the second argument of the callback. 您代码中的valindex ,您应该使用回调的第二个参数。

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

You can also use the this keyword. 您也可以使用this关键字。

Try this one : 试试这个:

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

You can use the each() function on your list: 您可以在列表中使用each()函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM