2013-03-12 55 views
0

你好,我有一個jQuery/Ajax的功能如下:閱讀JSON編碼數組形式CakePHP的視圖控制器

$.ajax({ 
    type : "POST", 
    url : "/posts/getids", 
    success: function(response){ 
     console.log(response);                 
    }, 
    error: function() { 
     alert('An unexpected error has occurred! Please try later.'); 
    } 
}); 

在我的CakePHP的劇本我送使用json_encode($陣列)功能的陣列。

在Firebug我得到這樣的結果:

[{"Post":{"id":1}},{"Post":{"id":2}},{"Post":{"id":4}},{"Post":{"id":3}}] 

所以我的問題是我如何可以簡單地只打印這樣的ID:1,2,3,4

謝謝。

回答

1
// Convert JSON to JavaScript array. 
var dataFromServer = JSON.parse(response); 

// Creating an array of id's. 
var idArray = []; 

// Moving data to "idArray". 
for(i = 0; i < dataFromServer.length; i++){ 
    idArray[i] = dataFromServer[i].Post.id; 
} 

// Checking the result. 
console.log(idArray); 

// [1, 2, 3, 4]. 
+0

謝謝你的工作! – OussamaLord 2013-03-12 18:15:21

+0

沒問題。如果你發現這個答案是正確的,請標記它。 – 2013-03-12 18:18:59

+0

主題已關閉。謝謝 – OussamaLord 2013-03-24 01:06:18