2012-03-06 8 views
1

どうすればいいですか?$ user jQueryの配列ですか? 'Failure'が返された場合、エラーを出力する必要があります。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

変数に名前を格納して後で出力する必要がありますが、** result = result + response.data [i] .name + '、' **は次のように表示されます:undefinedadmin_1、admin_2、admin_3 – BentCoder

+0

解決済み。私の間違い。 – BentCoder

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

感謝。これは非常に役に立ちます。 – BentCoder