2011-06-08 52 views
1

我使用JSON和JavaScript從連接到數據庫的php文件檢索數據。這是我的PHP代碼如何看起來像:如何從json_encode d數組中選擇元素?

while($row = $stmt->fetch_assoc()) { 
$data[] = $row; 
} 

header("Content-type: text/plain"); 
echo json_encode($data,true); 

這是我的javascript:

var displayfeeds = new ajaxObject('ajax/users/display.feeds.php'); 
displayfeeds.callback = function (responseText,status) { 
    var feed = JSON.parse(JSON.stringify(responseText)); 
    $("#feeds-feedback").html(feed); 
} 
displayfeeds.update(); 

當我運行它,它打印出一個這樣的數組:

[ 
    { 
     "userID":"39160902151", 
     "content":"bar bar bar bar", 
     "published":"2011-06-07 10:33:35" 
    }, 
    { 
     "userID":"5896858666", 
     "content":"foo foo foo foo foo", 
     "published":"2011-06-06 22:54:51" 
    } 
] 

我的問題是:那麼我該如何顯示「userID」和「content」? 我真的很掙扎。我是JSON新手。

+0

有沒有必要對你的JSON進行雙重編碼,擺脫'JSON.stringify()'調用。 'JSON.strigify()'是與PHP命令'json_encode()'等價的JavaScript。既然你收到它作爲一個字符串,你不需要在你的JS中做。 'JSON.parse()'接受一個JSON字符串並將其轉換爲一個對象,PHP具有一個名爲'json_decode()'的等價函數,如果您將JSON字符串傳遞迴PHP,則可以使用該函數。 – 2011-06-08 18:10:08

回答

0

要獲得第一個用戶ID:

var feed = JSON.parse(responseText); 
feed[0].userID 
+0

如何將此線程標記爲已解決? – Sthe 2011-06-08 18:15:21

+0

在每個答案中,您應該在分數下方看到一個灰色複選標記。點擊它來選擇該答案。 – 2011-06-09 09:53:59

1

您需要將JSON對象轉換成HTML格式來顯示它們。所以在你的回調函數中,我會這樣做:

displayfeeds.callback = function (responseText,status) { 
    var feed = JSON.parse(JSON.stringify(responseText)); 
    var html = ''; 

    // build html for each feed item 
    for (var i = 0; i < feed.length; i++) { 

     html += '<h3>UserID:: '+ feed[i]['userID'] +'</h3>'; 
     html += '<p>'+ feed[i]['content'] +'</p>'; 
     html += '<div><strong>published</strong>: '+ feed[i]['userID'] +'</div>'; 
     html += '<hr />'; 
    } 
    // append content once all html is built 
    $("#feeds-feedback").append(html); 
} 
+0

非常感謝。有效。我只需要刪除stringify並遵循你的兩個人的建議。謝謝 :-) – Sthe 2011-06-08 18:06:06