2

我将我的 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"
    }]
})

查询

 $(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;
 });
4

3 回答 3

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);
于 2012-06-26T14:57:09.543 回答
2

您想要的是重组 JSON,使其有效,然后一切正常。

这是显示示例的工作 jsFiddle。

于 2012-06-26T15:04:40.160 回答
0

JSON 键必须是唯一的,这在您的代码中并非如此。

于 2012-06-26T15:03:00.713 回答