我有一个 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 路由器设置来处理这个问题。