微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php-使用AJAX和Codeigniter从数据库中删除用户

我正在尝试使用AJAX和Code Igniter从数据库删除用户.当我单击删除链接时,用户将被删除,但页面将被重定向,并显示成功消息. AJAX在我的代码中似乎不起作用.
这是HTML

<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Username</th>
<th>Password</th>
<th>Action</th>
</tr>
</thead>
<tbody>




<?PHP foreach($users as $u){?>
<tr>



<td><?PHP echo $u['id']; ?></td>



<td><?PHP echo $u['firstname']; ?></td>



<td><?PHP echo $u['lastname']; ?></td>



<td><?PHP echo $u['email']; ?></td>



<td><?PHP echo $u['username']; ?></td>



<td><?PHP echo $u['password']; ?></td>



<td>



<a href="#" >Edit</a>  |
<?PHP  $id=$u['id'];?>
<a  href="<?PHP echo site_url("users/delete/$id")?>" class="delete">Delete</a>



</td>
<?PHP }?>
</tr>



</tbody>
</table>

这是AJAX:

 $(document).ready(function(){

     $(".delete").click(function(){
       alert("Delete?");
         var href = $(this).attr("href");
         var btn = this;

        $.ajax({
          type: "GET",
          url: href,
          success: function(response) {

          if (response == "Success")
          {
             $(btn).closest('tr').fadeOut("slow");
          }
          else
          {
            alert("Error");
          }

       }
    });

   })
  });

最后是控制器功能,可在Codeigniter中删除用户

 public function delete($id)//for deleting the user
  {
    $this->load->model('Users_m');

    $delete=$this->Users_m->delete_user($id);
      if($delete)
        {
          echo "Success";
        }
     else
        {
          echo "Error";
        }

  }

我在哪里犯错?

解决方法:

只是为了扩展此处已经给出的正确答案.

基本上,您的JS代码应如下所示:

$(document).ready(function(){

 $(".delete").click(function(event){
     alert("Delete?");
     var href = $(this).attr("href")
     var btn = this;

      $.ajax({
        type: "GET",
        url: href,
        success: function(response) {

          if (response == "Success")
          {
            $(btn).closest('tr').fadeOut("slow");
          }
          else
          {
            alert("Error");
          }

        }
      });
     event.preventDefault();
  })
});

这里的event.preventDefault()部分很重要.由于它阻止浏览器采取认操作,因此单击元素时将执行该操作.

如果是链接,那会将您重定向到href参数中定义的url.这就是您所看到的.

始终会首先触发您手动定义的事件,因此确实启动了ajax请求,但是在该事件处理程序之后,浏览器立即开始处理认操作,中断ajax请求,并导航到单击的链接.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐