jquery .getJSON输出所有数据.each

时间:2012-06-26 14:53:40

标签: jquery jsonp

我将我的php导出为jsonp,然后调用加载数据的js文件。

我只得到最后一个数据对象的输出。我想循环操作数据并将所有输出都输出到< li> data.action< / li> 格式。如果有人能帮助你知道如何做到这一点非常感谢你。

JSONP

({
    "posts": [{
        "action": "go to acting school",
        "action": "go to a beach",
        "action": "go kyacking",
        "action": "go skiing in vermont",
        "action": "sleep in a cave",
        "action": "dress up as favorite celebrity in public",
        "action": "see the cherry blossums in Washington DC",
        "action": "watch all the rocky movies",
        "action": "go sky diving",
        "action": "climb Mount Everest",
        "action": "climb K2",
        "action": "see or participate in war reenactment",
        "action": "spend New Years Eve in Times Square",
        "action": "jump out of a moving plane",
        "action": "jump out of a moving car",
        "action": "try eating a new food"
    }]
})

JQUERY

 $(document).ready(function () {
     $.getJSON("http://site.com/lesson.php?count=5&jsoncall=?", function (data) {
         $.each(data.posts, function (i, data) {
             var jsondata = "<li>" + data.action + "</li>";
             $(jsondata).appendTo("ol#results");
         });
     });
     return false;
 });

3 个答案:

答案 0 :(得分:5)

这不是正确的json。转换为javascript对象时,它将包含:

{
    "posts": [{"action": "try eating a new food"}]
}

这是我认为它应该是:

{
    "actions": ["go to acting school","go to a beach","go kyacking","go skiing in vermont","sleep in a cave","dress up as favorite celebrity in public","see the cherry blossums in Washington DC","watch all the rocky movies","go sky diving","climb Mount Everest","climb K2","see or participate in war reenactment","spend New Years Eve in Times Square","jump out of a moving plane","jump out of a moving car","try eating a new food"]
}

显然,这并不知道json究竟代表什么。我所做的改变背后的想法是,如果它们都是动作,将它们全部放在一个存储在名为actions的属性中的数组中

然后输出:

var myStr = "";
$.each(data.actions, function (i, action) {
    myStr += "<li>" + action + "</li>";
});
$("#results").append(myStr);

答案 1 :(得分:2)

你想要的是重构JSON以使它有效,然后事情就会好起来。

Here's the working jsFiddle showing the example.

答案 2 :(得分:0)

JSON密钥必须是唯一的,而代码中并非如此。