1

我刚开始使用 jquery 学习 json 并且遇到了一些困难,我花了两天时间,我在 youtube 和博客上都遵循了很多教程,但它们显示的并不是我所拥有的。他们的 json 和我的不一样。他们有多个钥匙我只有一个“新闻”

我得到的服务器的 JSON 响应是这样的:

{ 
    "news":[
        {
            "id":48927,
            "name": "The title goes right here",
            "url": "www.example.com",
            "date":"16 August 2013",
            "image":"img.example.com\/image.jpg"
        },
        {
            "id": 48908,
            "name":"The title goes right here — photography",
            "url":"www.example.net",
            "date":"17 August 2013",
            "image":"img.example.net\/image2.jpg"
        }
    ]
}

实际上我从服务器得到的更像是这样的:

{"news":[{"id":48927,"name": "The title goes right here","url": "www.example.com","date":"16 August 2013","image":"img.example.com\/image.jpg"},{"id": 48908,"name":"The title goes right here — photography","url":"www.example.net","date":"17 August 2013","image":"img.example.net\/image2.jpg"}]}

但它们都有效!我已经检查过 JSON LINT。

所以我不能做的是从 JSON 中获取所有信息并将它们附加到我的#posts

我已经尝试过$.getJSON$.ajax但我得到未定义的响应

$(document).ready(function() {

    $.ajax({
        url: 'http://s.example.com/myjson.php',
        data: 'GET',
        dataType: 'json',

        success: function(data){
            $('#posts').append('name: ' + data.news.id + '<br/>');
        },
    });

});

in code above I've tried in append also with data, data.id, data.news, data.url etc. but alway getting undefined or null.

$(document).ready(function() {

    $.getJSON("http://s.example.com/myjson.php", function(data) {
        $.each(data, function(key, value) {
            $("#posts").append("<li>"+data.news+"</li>");
        });
    });


});

same as $.ajax tried different things in append but nothing.

what I want to do is to have all the data id, name, url, date, image appended for everyone of the "things" I've in my json file. But unfortunately I'm stuck at the beginning. It's really frustrating, because it seems so simply but I can't figure out a way to do it. Please help me!!

4

3 回答 3

1

Inside your success function, loop over all of the elements in the news array:

for (var i=0; i < data.news.length; i++) {
    $('#posts').append('name: ' + data.news[i].id + '<br/>');
}
于 2013-08-15T16:08:20.517 回答
0

In your JSON, news is an array.

You need to get the property from an element in the array:

data.news[42].id

You will need to figure out which element to get.

于 2013-08-15T16:01:38.517 回答
0

data.news is an array so you have to loop through it to get all the values

$(document).ready(function() {

    $.getJSON("http://s.example.com/myjson.php", function(data) {
        $.each(data.news, function(key, value) {
            $("#posts").append("<li>"+value.id+"</li>");
        });
    });


});
于 2013-08-15T16:02:59.883 回答