【问题标题】:How to parse JSON returned in array?如何解析数组中返回的 JSON?
【发布时间】:2013-04-05 13:04:45
【问题描述】:

我有一个 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: Unexpected end of input”,将我指向括号所在的最后一行数据。 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 路由器设置来处理这个问题。

【问题讨论】:

标签: php jquery json jsonp


【解决方案1】:

下面是一个使用回调函数响应 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,这很有趣。

【讨论】:

  • 好的。通过使用 $.ajax 的固定回调,我几乎已经弄清楚了。但是,由于我将 URL 路由到 PHP 文件(例如:/api/posts/add -> /api/add.php),因此我无法使用 GET 请求。有没有办法避免使用基于 GET 的回调?
  • 那是为了使用不同的回调。
  • 将 URL 路由到 PHP 文件是什么意思?您是否正在为 post/put 等实现 REST API?
猜你喜欢
  • 2015-05-01
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多