jQuery 的 $.ajax 方法不适用于 JavaScript confirm() 方法

jQuery's $.ajax method does not work with JavaScript confirm() method

我正在使用 Codeigniter 3.1.8 和 Bootstrap 4.

开发基本的 博客应用程序

该应用程序具有删除 post 功能。我在通过 jQuery 的 $.ajax 方法删除 post 时卡住了。

post 的视图如下所示:

<table class="table table-striped table-sm border-0">
  <thead>
    <tr>
      <th>#</th>
      <th class="w-50">Title</th>
      <th>Publication date</th>
      <th class="text-center">Actions</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($posts as $index => $post): ?>
    <tr id="<?php echo $post->id; ?>">
      <td class="text-right"><?php $count = $index + 1; echo $count + $offset; ?></td>
      <td><?php echo $post->title; ?></td>
      <td><?php echo nice_date($post->created_at, 'D, M d, Y'); ?></td>
      <td class="text-center">
        <div class="btn-group btn-group-sm" role="group">
          <a href="<?php echo base_url('posts/post/') . $post->id; ?>" class="btn btn-success"><i class="fa fa-eye"></i> View</a>
          <?php if($this->session->userdata('is_logged_in') && $this->session->userdata('user_id') == $post->author_id) : ?>
          <a href="<?php echo base_url('posts/edit/') . $post->id; ?>" class="btn btn-success"><i class="fa fa-pencil-square-o"></i> Edit</a>
          <a href="#" id="delete_post" data-id="<?php echo $post->id ?>" class="ajax-btn btn btn-success"><i class="fa fa-trash"></i> Delete</a>
          <?php else: ?>
          <a href="#" class="btn btn-success disabled"><i class="fa fa-pencil-square-o"></i> Edit</a>
          <a href="#" id="delete_post" class="btn btn-success disabled"><i class="fa fa-trash"></i> Delete</a>
          <?php endif; ?>
        </div>
      </td>
    </tr>
    <?php endforeach ?>
  </tbody>
</table>

jQuery 意味着通过 $.ajax:

删除 posts
//Delete Posts
$('#delete_post').on('click', function(evt){
    evt.preventDefault();
    var deleteUrl = $(this).attr('href');
    var id = $(this).data('id');

    if(confirm('Delete this post?')) {
      if ($(this).hasClass("ajax-btn")) {
        $.ajax({
          url: 'posts/delete/' + id,
          method: 'GET',
          dataType: 'html',
          success: function(deleteMsg){
            $('tr#' + id).fadeOut('250');
            $('#delete_msg').html('<p>Post successfully deleted</p>');
            $('#delete_msg').slideDown(250).delay(2500).slideUp(250);
          }
        });
      } else {
        window.location.href = deleteUrl;
      }
    }

});

上面的代码由于某种原因无法运行。我哪里错了?

您不能在多个元素上使用相同的 id。相反,给你的删除按钮 class:

<a href="#" id="delete_post" data-id="<?php echo $post->id ?>" class="delete-post ajax-btn btn btn-success">

...然后使用 .delete_post 而不是 #delete_post:

$('.delete_post').on('click', function(evt){