dongzong3053 2013-04-12 21:12
浏览 106

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

I have a PHP backend, which when queried, will return a set of posts in JSON. But, since there are multiple posts, it is in an array. Ex: (The string at the beginning is just a JSONP callback)

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

Note how the JSON is surrounded by brackets. When I use a jQuery script to call and parse this data, I get the error "Uncaught SyntaxError: Unexpected end of input," pointing me to the last line of data where the bracket is. 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+")");
        });
    });
});

And finally, here is the PHP sending the JSON:

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).")";

The callback variable is functioning. I have a simple PHP router setup that handles that.

  • 写回答

1条回答 默认 最新

  • duanli6834 2013-04-12 21:15
    关注

    Here is an example of a response to JSONP call with callback and how it should be returned (in this case CouchDB):

    Request:

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

    Response:

    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
            }
        }
    });
    

    Try adding a semicolon at the end and the ? _ in your generated response should be removed as it makes Javascript thing there is a comparison happening.

    Your response should be like this:

    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"
                    }
                }
            ]);
    

    Finally, you could have a look at https://stackoverflow.com/a/1678243/1688441 which is very interesting.

    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)