我有一個PHP後端,當查詢時,將返回一組JSON中的帖子。但是,因爲有多個帖子,所以它是在一個數組中。例如:(開頭的字符串只是一個JSONP回調)如何解析數組中返回的JSON?
jQuery19107630979726091027_1365800375610?_=1365800375611([
{
"content": "Hello",
"time": "1349829544",
"info": {
"email": "[email protected]",
"username": "test",
"first": "Test",
"last": "User",
"id": "2"
}
},
{
"content": "test.",
"time": "1349829535",
"info": {
"email": "[email protected]",
"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+")");
});
});
});
最後,這裏是PHP發送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).")";
回調變量起作用。我有一個簡單的PHP路由器設置來處理它。
你沒有正確地做jsonp。 jquery有一個特定的格式,它尋找做一個jsonp請求:http://stackoverflow.com/questions/2681466/jsonp-with-jquery –
我建議他也看看http://stackoverflow.com/questions/1678214/javascript-how-do-i-create-jsonp,它解釋瞭如何創建一個JSONP接口。 –