2012-03-06 77 views
1

如何循環訪問jQuery中的這個$ user數組?如果'失敗'返回,則應打印錯誤。通過jQuery中的數組循環遍歷

Solution here實際打印,但與此輸出這是錯誤的:undefinedadmin_1,admin_2,admin_3

在此先感謝

<?php 
$id = $_POST['id']; 

if($id == 1) 
{ 
    $users['data'] = array(array('name'=> 'admin_1'), array('name'=> 'admin_2'), array('name'=> 'admin_2')); 
    echo json_encode($users); 
} 
else 
{ 
    $users['data'] = 'Failure'; 
    echo json_encode($users); 
} 
?> 



$.ajax({ 
    type  : 'POST', 
    url   : 'list.php', 
    data  : 'id=' + text_id, 
    dataType : 'json', 
    success  : function(response) 
    { 
     //IF not 'Failure', loop through the array and print content into div.success 
     //IF 'Failure', show div.fail 
    } 
}); 

回答

1
if(response.data == 'Failure') { 
    console.log('error'); 
    return false; 
} 

for(var i = 0; i < response.data.length; i++) { 
    if(typeof response.data[i].name != 'undefined') { 
     console.log(response.data[i].name); 
    } 
} 
+0

我必須將名稱存儲在一個變量中,然後打印它,但**結果=結果+ response.data [i] .name +','; **打印它像這樣:undefinedadmin_1,admin_2,admin_3 – BentCoder 2012-03-06 11:08:39

+0

好的解決了。我的錯。 – BentCoder 2012-03-06 11:39:41

1
if ($.isArray(response)) { 
    //loop through array 
} else { 
    //show error 
} 
+0

感謝。這非常有幫助。 – BentCoder 2012-03-06 11:09:24