2012-04-06 129 views
0

可能重複:
Json Returning [object object] instead of array數組返回[Object object]而不是數值?

我有一個包含一個子陣列,陣列經由POST請求的PHP文件拉動。問題是,我很難找到如何返回數組對象的值,更不用說遍歷它了。

的Javascript

$.ajax({ 
    type: 'POST', 
    url: 'php.php', 
    data: 'id=testdata', 
    dataType: 'json', 
    cache: false, 
    success: function(result) { 
     alert(result[0]); // returns [Object object] 
    }, 
}); 

我相信它是正確抓取從PHP文件中的數組。

這是the PHP file

+0

你期望它的結果是什麼? – Bazzz 2012-04-06 20:27:01

+0

http://stackoverflow.com/questions/7620953/json-returning-object-object-instead-of-array – c69 2012-04-06 20:33:31

回答

0

可以遍歷它想:

$.each(result, function() { 
    alert(this.name); // or this.id, this.description, etc. 
}); 

我建議使用的工具(如Firebug),然後做console.log(result);得到一個更具描述性的輸出。

3

在你的情況下,result是一個對象數組,所以result[0]是第一個對象。例如,要訪問id,您可以使用result[0]['id']。爲了通過對象數組進行迭代,你可以使用一個for循環像這樣的例子:

for(var i=0, len = result.length; i<len; i++) { 
    //write your code for each object in the results here 
    var id = result[i]['id']; 
} 
2

您必須在指定對象,至極一個展示,我的意思是....

alert(result[0]['field_name']); 

當您使用PHP來從一個「ID」一些數據,我可以通知您,quering MySQL時,使用下一個語法,

echo json_encode(mysql_fetch_object(mysql_query('your_query'))); 

有了這個SYNT斧頭你會得到一個只在您的查詢獲取的所有字段對象,因此警報將是:

alert(result['field_name']); 

我希望這有助於。

相關問題