首页 > 解决方案 > 如何在 Ajax Jquery 方法中使用 setTimeout() 防止关闭模式?

问题描述

我正在尝试使index.php页面“自动”每 2 秒从 MySQL 表中加载数据,使用setTimeout(). 问题是每次我从第二页(order.php)单击查看详细信息按钮时,模式加载但 2 秒后立即关闭。

当我单击查看详细信息按钮并在关闭模式后继续刷新 div 以从 MySQL 表中加载数据时,如何防止自动关闭模式?

index.php(第一个 php 页面)

 // INDEX.PHP
 <body>
    <div id = "showCustomerOrder_div"></div>
 </body>

 <script>
 var interval = 2000;
 function displayCustomerOrder() {
$.ajax({
    type: 'POST',
    url: 'order.php',
    data: { },
    success: function (data) {
        $('#showCustomerOrder_div').html(data);
    },
    complete: function (data) {
        setTimeout(displayCustomerOrder, interval);
    }
});
 }
 setTimeout(displayCustomerOrder, interval);
 </script>

order.php(第二个 php 页面)

 // ORDER.PHP
 <?php
  $count = 0;
 while ($rows = mysqli_fetch_array($query)) {
  $count++;
  $date = $rows['date_order'];
  $receipt = $rows['receipt_no'];
  $fullname = $rows['fullname'];
  $restoname = $rows['resto_name'];
  $total = $rows['Total'];
 ?>
<tr>
    <td><?php echo $count; ?></td>
    <td><?php echo date_format($date,"m/d/y h:i:s"); ?></td>
    <td><?php echo $receipt; ?></td>
    <td>
    <a href = "#orderDetails<?php echo $receipt; ?>" data-toggle = "modal" class = "btn btn-primary">View Details</a>
    </td>
</tr>

    <div class = "modal" id = "orderDetails<?php echo $receipt; ?>">
        <div class = "modal-dialog">
            <div class = "modal-content">
                <div class = "modal-header">
                </div>
                <div class = "modal-body">
                    <div class = "row">                     
                      <div class = "col"><?php echo $rows['receipt_no']; ?></div>
                      <div class = "col"><?php echo $rows['fullname']; ?> </div>
                      <div class = "col"><?php echo  $rows['Total']; ?> </div>
                    </div>
                </div>
                <div class = "modal-footer">
                </div>
            </div>
        </div>
    </div>
 <?php
}
 ?>    

非常感谢!

标签: javascriptphpjquerymysqlajax

解决方案


像这样的东西

$("#container").on("click","[data-toggle=modal]",function(e) {
  e.preventDefault();
  var texts = $(this).closest("tr").find("td").map((_, cell) => cell.innerText).get(); 
  texts.pop(); // lose the link text
  $(".row").empty();
  $.each(texts, (_, text) => $(".row").append(`<div class="col">${text}</div>`));
})  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <table>
    <tr>
      <td>One</td>
      <td>2019 05 10</td>
        <td>receipt 1</td>
        <td>
          <a href="#" data-toggle="modal" class="btn btn-primary">View Details</a>
        </td>
    </tr>
    <tr>
      <td>Two</td>
      <td>2019 05 11</td>
        <td>receipt 2</td>
        <td>
          <a href="#" data-toggle="modal" class="btn btn-primary">View Details</a>
        </td>
    </tr>
  </table>
</div>
<div class="modal-body">
  <div class="row">
  </div>
</div>


推荐阅读