试图将数组返回到表中的列表

时间:2013-08-26 20:55:48

标签: php javascript jquery ajax

Jquery - 我得到了未定义但是在php中给出了我的表信息的响应。

function formfill(dblist) {
    var tableheader = "<thead><tr><th>Database Nick</th><th>Database IP</th> <th></th></tr></thead>";

    $('#table2').empty();
    $('#table2').append(tableheader);

    $.each(dblist, function (key, value) {
        $('#table2').append('<tr><td>' 
        + dblist['DBNick'] 
        + '</td><td>' 
        + dblist['DBIP'] 
        + '</td><td><input class="add" id="add" name="add" value="add" type="submit"></input></td></tr>');

    }); 
}

$('#userlist').on('change', function () {
    var selected = $('#userlist').val();

    console.log(selected);

    $.ajax({
        url: '/php/user/userdbtable.php',
        type: 'POST',
        data: { user: selected },
        success: function (data) {
            formfill(data)
        },
        error: function (xhr, status, err) { console.log(xhr, status, err); }
    });
});

这是发送正确数据的php,但我无法弄清楚如何从对象中提取它。

<?php 
session_start(); 

include '../connect/anonconnect.php'; 

$myusername= $_POST['user'];

$useridsql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$useridsql->execute(array(':login' => $myusername));
$useridsql = $useridsql->fetch();

$userid = $useridsql['idUser'];

$query = 'SELECT * FROM DBList  INNER JOIN UserDBList 
    ON DBList.idDatabase = UserDBList.idDatabase ';//WHERE UserDBList.idUser = '.$userid; 
$sql = $dbh->prepare($query); 
$sql->bindParam(':username', $myusername, PDO::PARAM_STR, 12); 
$sql->execute(); 
$user = $sql->fetchAll(PDO::FETCH_ASSOC); 

if($sql->rowCount() == 1){ 
    header('Content-type: application/json'); 
    echo json_encode($user,JSON_FORCE_OBJECT); 
} 
else { 
    echo 0; 
}   
?>

1 个答案:

答案 0 :(得分:2)

我认为你的循环有错误。它应该是这样的:

$.each(dblist, function (index, item) {
    $('#table2').append('<tr><td>' 
        + item['DBNick'] 
        + '</td><td>' 
        + item['DBIP'] 
        + '</td><td><input class="add" id="add" name="add" value="add" type="submit"></input></td></tr>');

});