Jquery / Ajax请求替换Json feed中的空数组

时间:2013-03-27 21:59:49

标签: jquery ajax json

我试图在我的json中识别一些空数组,然后放置一个div。在脚本看到空数组时,它会停止加载json。代码是:

$.each(data.posts, function (i, item) {
    var newstitle = item.title;
    var newstmbn = item.thumbnail;

    if (data !== undefined && data.posts !== undefined && data.posts.attachments !== undefined) {
        $.each(item.attachments, function (i2, type) {
            $('#news').append('<div>' + item.thumbnail + '</div>');
        });
    } else {
        $.each(item.attachments, function (i2, type) {
            $('#news').append('<div>' + type.images.thumbnail.url + '</div>');
        });
    }
    output.append(news);

});

我的json看起来像:

{
    "posts": [
    {
        "id": 914,
        "title": "post1",
        "thumbnail": "\/uploads\/url.jpeg",
        "attachments": [
        {
            "images": {
                "thumbnail": {
                    "url": "\/uploads\/url-150x92.jpeg"
                }
            }
        }
        ]
    },
    {
        "id": 915,
        "title": "post1",
        "thumbnail": "\/uploads\/url.jpeg",
        "attachments": []
    },
    {
        "id": 914,
        "title": "post1",
        "thumbnail": "\/uploads\/url.jpeg",
        "attachments": [
        {
            "images": {
                "thumbnail": {
                    "url": "\/uploads\/url-150x99.jpeg"
                }
            }
        }
        ]
    }
]}

所以你可以看到一些“附件”是空的,我想放置“item.thumbnail”,但它似乎不起作用。你能帮我吗?

1 个答案:

答案 0 :(得分:2)

我认为你的主要问题是这一行:

 if (data !== undefined && data.posts !== undefined && data.posts.attachments !== undefined)

这是放在.each循环中迭代data.posts数组。

if (data !== undefined && data.posts !== undefined)

应放在该循环之外,以测试是否可以进行循环。

data.posts.attachments !== undefined

没有任何意义,因为data.posts是一个数组,因此没有附件属性。那应该是

if(item.attachments !== undefined)

如果这是假的,即项目没有附件,则不能像当前那样迭代item.attachments。此外,你已经得到了if / else错误的方法,所以替换

$.each(item.attachments, function (i2, type) {
    $('#news').append('<div>' + type.images.thumbnail.url + '</div>');
});

$('#news').append('<div>' + item.thumbnail + '</div>');

$.each(item.attachments, function (i2, type) {
    $('#news').append('<div>' + item.thumbnail + '</div>');
});

$.each(item.attachments, function (i2, type) {
    $('#news').append('<div>' + type.images.thumbnail.url + '</div>');
});

编辑:因为我意识到上面的内容可能很难理解,所以我认为这是正确的代码:

if (data !== undefined && data.posts !== undefined) {
    $.each(data.posts, function (i, item) {
        if (item.attachments !== undefined && item.attachments.length > 0) {
            $.each(item.attachments, function (i2, type) {
                $('#news').append('<div>' + type.images.thumbnail.url + '</div>');
            });
        } else {
            $('#news').append('<div>' + item.thumbnail + '</div>');
        }
        output.append(news); //I assume output is a valid jquery object...
    });
}

http://jsfiddle.net/Jh3hk/

的概念证明