【问题标题】:Loop through an array in jQuery循环遍历jQuery中的数组
【发布时间】:2012-03-06 10:38:53
【问题描述】:

如何在 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
    }
});

【问题讨论】:

    标签: jquery arrays loops


    【解决方案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);
        }
    }
    

    【讨论】:

    • 我必须将名称存储在一个变量中,然后打印出来,但是 result = result+response.data[i].name + ', '; 打印出来是这样的:未定义admin_1,admin_2,admin_3
    【解决方案2】:
    if ($.isArray(response)) {
        //loop through array
    } else {
        //show error
    }
    

    【讨论】:

    • 谢谢。这很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 2019-03-25
    • 2017-01-29
    • 2014-05-01
    • 1970-01-01
    相关资源
    最近更新 更多