使用 PHP、SQL 和 AJAX 方法的模态

Modal with PHP, SQL & AJAX METHOD

谁能告诉我这段代码有什么问题?我正在尝试根据模态形式的用户名更新我的 SQL。我需要在每一行都有一个模式弹出窗口,并根据用户名更新特定用户。

这是我的完整代码:

<?php
function build_table($result){
    if(mysqli_num_rows($result) > 0){
        echo "<table class='tbl'>";
        echo "<tr>";
        echo "<th>Username</th>";
        echo "<th>User type</th>";
        echo "<th>Status</th>";
        echo "<th>Created by</th>";
        echo "<th>Change Status</th>";
        echo "<th>Actions</th>";
        echo "</tr><br>";
        while($row = mysqli_fetch_array($result)){
        echo "<tr>";
        echo "<td>" . $row['username'] . "</td>";
        echo "<td>" . $row['usertype'] . "</td>";
        echo "<td>" . $row['status'] . "</td>";
        echo "<td>" . $row['createdby'] . "</td>";
        echo "<td>";
        echo "<a data-toggle='modal' id='up_modal' href = '#myModal' data-username = '". $row['username'] . "'>Activate </a>";
  ?>

模态:

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Activate Account</h4>
        </div>
        <div class="modal-body">
            <div id="showcal"></div>
         </div>
        </div>
      </div>
    </div>
</div>

这里是js函数:

<script>
$(document).ready(function(){
    $('#myModal').on('shown.bs.modal', function () {
       var username = $("#up_modal").attr('data-username')
           $.ajax({
                type: 'GET',
                url:'activate-account.php?username='+username,
                success:function(data){
                    $('#showcal').html(data);
                }
         });
     });
 });
 </script>

我认为在尝试使用 PHP 查询获取用户名 url:'activate-account.php?username='+'<?php echo $row['username'];?>', 时出错了 在 Ajax 请求中,你可以给锚标签指定的 id 并将用户名值放在新属性中,如下面的代码

echo "<a data-toggle='modal' id='up_modal' href = '#myModal' data-username = '".<?php echo $row['username'];?>."'>Activate </a>";

and In JavaScript 通过以下代码获取值:

$(document).ready(function(){
    $('#myModal').on('shown.bs.modal', function () {
       var username = $("#up_modal").attr('data-username')
        $.ajax({
            type: 'GET',
            url:'activate-account.php?username='+username,
            success:function(data){
            $('#showcal').html(data);
         }
       });
    });
});

或者您可以像在锚标记中那样通过查询字符串获取它,您将用户名作为查询字符串传递,这样您就可以在 js 函数中执行以下代码

$(document).ready(function(){
    $('#myModal').on('shown.bs.modal', function () {
       var url_string = window.location.href
       var url = new URL(url_string);
       var username = url.searchParams.get("username");
        $.ajax({
            type: 'GET',
            url:'activate-account.php?username='+username,
            success:function(data){
            $('#showcal').html(data);
         }
       });
    });
});