【问题标题】:How to insert while loop data of php in jQuery array?如何在jQuery数组中插入php的while循环数据?
【发布时间】:2018-09-13 12:48:11
【问题描述】:

我想在 jQuery 数组中插入 while 循环用户数据。

<?php 

    while($get_users_table_details = mysql_fetch_array($deatails)) {


        if(empty($get_users_table_details["photo"])) { $pics = "photos/avatar.gif"; } else { $pics = "photos/".strip_tags($get_users_table_details["photo"]).""; }

        ?>

while循环之间的脚本代码

$(document).ready(function(){

        $("#full").mention({
            users: [{
                name: '<?php echo $get_users_table_details['fullname'];?>',
                username: '<?php echo $get_users_table_details['username'];?>',
                image: '<?php echo $pics;?>'
                   }]     });
});
    </script>

end of script

}
end of while loop

问题在于这仅显示了一个用户的用户详细信息。但是,我希望显示所有用户详细信息,如下图所示:

【问题讨论】:

  • 您应该将循环迭代到 javascript 代码而不是 PHP 代码中。并且需要将每个元素都推送到用户 javascript 数组中。
  • 请提供您的PHP数组数据结构。
  • id、用户名、图片、全名、
  • 完全在 php 中构建 users 数组,然后 json_encode 整个事情并将其“传递”给 js。让 JavaScript 退出 while 循环。

标签: php jquery arrays while-loop


【解决方案1】:

你应该首先在 php 中构建用户数组:

<?php

$users = []; // instatiate an empty array

while($get_users_table_details = mysql_fetch_array($deatails)) {
    // build a user-array as needed later
    $user = [];
    $user['name'] = $get_users_table_details['fullname'];
    $user['username'] = $get_users_table_details['username'];
    if(empty($get_users_table_details["photo"])) { 
         $user['image'] = "photos/avatar.gif"; 
    } else { 
         $user['image'] = "photos/".strip_tags($get_users_table_details["photo"]); 
    }
    $users[] = $user;  // add this user to the array of users
}
?>

然后通过 json_encode 将 (=echo) 传递给 javascript:

<script>
$(document).ready(function(){

    $("#full").mention({
        users: <?php echo json_encode($users); ?>
    });
});
</script>

【讨论】:

    【解决方案2】:

    请试试这个示例 javascript 代码。

        var users = <?php echo json_encode($get_users_table_details ) ?>;
        $.each(users, function(key, value) {
            console.log('stuff : ' + key + ", " + value);
            // Do everything you want
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-21
      • 2020-05-13
      • 2019-04-30
      • 1970-01-01
      • 2012-04-23
      • 2019-01-21
      • 1970-01-01
      • 2018-10-04
      相关资源
      最近更新 更多