2012-03-06 82 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