在jQuery中循环遍历数组

时间:2012-03-06 10:38:54

标签: jquery arrays loops

如何在jQuery中循环遍历 $ user 数组?如果“失败”返回,则应打印错误。

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
    }
});

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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);
    }
}