如何解析数组中返回的JSON?

时间:2013-04-12 21:12:54

标签: php jquery json jsonp

我有一个PHP后端,在查询时,将返回JSON中的一组帖子。但是,由于有多个帖子,因此它位于一个数组中。例如:(开头的字符串只是一个JSONP回调)

jQuery19107630979726091027_1365800375610?_=1365800375611([
    {
        "content": "Hello",
        "time": "1349829544",
        "info": {
            "email": "test@test.com",
            "username": "test",
            "first": "Test",
            "last": "User",
            "id": "2"
        }
    },
    {
        "content": "test.",
        "time": "1349829535",
        "info": {
            "email": "test@test.com",
            "username": "test",
            "first": "Test",
            "last": "User",
            "id": "2"
        }
    }
])

注意JSON是如何用括号括起来的。当我使用jQuery脚本来调用和解析这些数据时,我收到错误“Uncaught SyntaxError:意外的输入结束”,指向括号所在的最后一行数据。 JS:

$("#getPosts").click(function(){
    $.getJSON("http://mysite.com/api/posts/list/byfriends/callback=?", function(data){
        $.each(data, function(){
            $('#posts').append("<li><p>"+this.content+"</br>By: "+this.info.first+" "+this.info.last+" ("+this.info.email+")");
        });
    });
});

最后,这是发送JSON的PHP:

include('config.inc');
header("Content-type: text/javascript");
$posts = array();
$subscribe = "SELECT subscribed FROM subscribe WHERE subscriber = '{$_SESSION['id']}'";
$query = mysql_query("SELECT * FROM `posts` WHERE (`post_owner` IN ({$subscribe}) OR `post_owner` = {$_SESSION['id']}) ORDER BY `id` DESC");
$num = mysql_numrows($query);
for ($i = 0; $i < $num; $i++) {
    $post['content'] = mysql_result($query, $i, 'content');
    $post['time'] = mysql_result($query, $i, 'timestamp');
    $post['info'] = getInfo_other(mysql_result($query, $i, 'post_owner'));
    array_push($posts, $post);
}
echo $callback."("json_encode($posts, JSON_PRETTY_PRINT).")";

回调变量正在运行。我有一个简单的PHP路由器设置来处理它。

1 个答案:

答案 0 :(得分:0)

以下是使用回调对JSONP调用的响应以及如何返回它的示例(在本例中为CouchDB):

请求:

http://whatever.com/couchdb/db/2010-07-09T23%3A57%3A38.500000Z?callback=a

响应:

a({
    "_id" : "2010-07-09T23:57:38.500000Z",
    "_rev" : "1-750aa2bc0a40e32120e8f6af49b7e979",
    "timestamp" : 2500,
    "data" : {
        "time" : "2010-07-09T23:57:38.500000Z",
        "audio" : {
            "crowd_score" : 0.012911000000000001,
            "traffic_score" : 0.155251,
            "applause_score" : 0.0,
            "music_score" : 0.22573499999999999,
            "@ID" : "freesound_org_100840",
            "position" : 2.5
        }
    }
});

尝试在结尾添加分号和?应该删除生成的响应中的_,因为它会使Javascript事情发生比较。

您的回答应该是这样的:

jQuery19107630979726091027_1365800375610([{
                "content" : "Hello",
                "time" : "1349829544",
                "info" : {
                    "email" : "test@test.com",
                    "username" : "test",
                    "first" : "Test",
                    "last" : "User",
                    "id" : "2"
                }
            }, {
                "content" : "test.",
                "time" : "1349829535",
                "info" : {
                    "email" : "test@test.com",
                    "username" : "test",
                    "first" : "Test",
                    "last" : "User",
                    "id" : "2"
                }
            }
        ]);

最后,你可以看一下非常有趣的https://stackoverflow.com/a/1678243/1688441