单击“查看潜在客户”按钮时出现多个 AJAX 请求 - 如何只发送一个请求?

Multiple AJAX Requests When Clicking 'View Leads' Button - How to Send Only One Request?

提问人:Aamir Khan 提问时间:8/7/2023 最后编辑:Aamir Khan 更新时间:8/7/2023 访问量:30

问:

单击我的 Web 应用程序上的“查看潜在客户”按钮时,它会发送多个具有相同数据的 AJAX 请求,而不仅仅是一个。我正在使用jQuery,并且尝试使用标志来防止同时请求,但问题仍然存在。如何解决此问题以确保每次单击仅发送一个 AJAX 请求?任何帮助将不胜感激。谢谢!

<script>  jQuery(document).ready(function($) {
    // Flag to track if an AJAX request is in progress
    let isRequestInProgress = false;

    // Function to handle the click event on the "View Leads" button
    function handleViewLeadsClick(carId) {
      // Check if an AJAX request is already in progress
      if (isRequestInProgress) {
        return;
      }

      // Set the flag to true to indicate that an AJAX request is in progress
      isRequestInProgress = true;

      // Make an AJAX request to the server
      $.ajax({
        type: "POST",
        url: "https://mywebsite.ca/ajax2.php",
        data: { carId: carId },
        dataType: "json",
        success: function(response) {
          // Reset the flag to false after the AJAX request is completed
          isRequestInProgress = false;

          // Check if the response contains data
          if (response && response.data) {
            // Create an HTML table to display the data
            let tableHtml = '<table id="leads-table" class="display nowrap" style="width: 100%"><thead><tr><th>ID</th><th>Mobile</th><th>Time</th><th>Status</th></tr></thead><tbody>';

            // Loop through the data and add rows to the table
            response.data.forEach(function(item) {
              tableHtml += '<tr><td>' + item.id + '</td><td>' + item.mobile + '</td><td>' + item.time + '</td><td>' + item.status + '</td></tr>';
            });

            // Close the table body and table tag
            tableHtml += '</tbody></table>';

            // Display the table using SweetAlert2 with custom width
            Swal.fire({
              title: 'Leads Data',
              html: tableHtml,
              confirmButtonText: 'Close',
              customClass: {
                // Add a custom CSS class to control the width of the modal
                container: 'custom-sweetalert2-container'
              },
              // Adjust the width for different screen sizes
              width: '90%', // Set the initial width of the modal
              responsive: true, // Allow responsiveness for mobile devices
              // Optional breakpoint settings for responsiveness
              breakpoints: {
                768: { // Set breakpoint for screens smaller than 768px (e.g., mobile devices)
                  width: '95%' // Adjust width for mobile devices
                }
              }
            });

            // Initialize DataTable on the created table
            $('#leads-table').DataTable({
              scrollX: true,
              scrollCollapse: true,
              autoWidth: false
            });
          }
        },
        error: function() {
          // Reset the flag to false after the AJAX request is completed
          isRequestInProgress = false;

          // Handle the error if the AJAX request fails
          Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: 'Something went wrong while fetching data!',
            confirmButtonText: 'Close'
          });
        }
      });
    }

    // Attach the click event handler using event delegation to the parent element
    $(document).on('click', '.view-leads-btn', function(e) {
      e.preventDefault(); // Prevent the default anchor click behavior
      const carId = $(this).data('carid'); // Get the data-carid attribute value
      handleViewLeadsClick(carId); // Call the function to handle the click event
    });
  });
</script>```

View Leads Button repeats multiple time on same page.


```<span class="vehica-panel-card__action">
                <a href="#" class="view-leads-btn" data-carid="<?php echo $vehicaCar->getId(); ?>">
                    <i class="fas fa-users"></i>
                    <?php echo "View Leads"; ?>
                </a>
            </span>```




Attempted to prevent multiple AJAX requests using the isRequestInProgress flag. Expected one AJAX request per click on the "View Leads" button, but multiple requests are still being sent.




javascript jquery css ajax

评论

0赞 IT goldman 8/7/2023
您正在使用事件委派,但从未引用哪个元素是单击的元素。e.target
0赞 Harshit verma 8/7/2023
简单的解决方案是在 ajax 调用之前禁用按钮,并在使用 jquery 从 ajax 调用中获得回报时启用,$('#buttonID').prop('disabled', true/false)

答: 暂无答案