使用codeigniter确认并删除记录。在javascript中有问题确认删除记录并重定向到相同的控制器/索引方法

时间:2017-03-29 14:23:59

标签: codeigniter

我是codeigniter的新手。删除我的表记录后,我想重定向到相同的控制器索引方法。记录已成功删除但重复显示警报消息。相反redirect()方法我使用javascript确认方法删除它将一次又一次显示警告框。如果我尝试redirect()方法,它不显示确认警告框。如果我尝试使用确切的base_url()方法进行重定向,则会移至URL:http://localhost/codeigniter/category/remove_category/25并且页面为空。我尝试了很多方法。我不知道为什么重复显示确认警报框。请建议我。提前谢谢。

查看代码

<table border="1">  
<tbody>  
    <tr>  
        <td>Category Id</td>  
        <td>Category Name</td>
        <td>Click Edit Link</td>
        <td>Click Delete Link</td>  
    </tr>  
    <?php

    foreach ($category->result() as $row)  
    {  
        ?><tr>  
            <td><?php echo $row->category_id;?></td>  
            <td><?php echo $row->category_name;?></td>
            <td><a href="<?=base_url()?>category/edit_category/<?=$row->category_id?>">Edit</a></td>
            <td><a href="<?=base_url()?>category/remove_category/<?=$row->category_id?>">Delete</a></td>  
        </tr>  
        <?php 
    }
    ?>  
</tbody>  
</table>

控制器代码

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Category extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->load->model('category_model');

}

function index(){

    $data['category']=$this->category_model->show_category();  
    //return the data in view  
    $this->load->view('categories_view', $data);

}

function remove_category($category_id){

    if($this->category_model->delete_category($category_id))
    {
    /*echo "<script type='text/javascript'> confirm('Are you sure to delete permanently?');
    window.location.href='index'";*/
   //redirect(base_url().'category');

    echo "<script>
                    confirm('Are you sure to delete permanently?!');
                    window.location.href = '" . base_url() . "category';
                </script>";
    }       
}

}

型号代码

class Category_model extends CI_Model {

function show_category(){

    $query = $this->db->get('tbl_category');
    return $query;

}

function insert_category($data){

    $this->db->insert('tbl_category', $data);
    return $this->db->insert_id();
}

function delete_category($category_id){
    $this->db->where('category_id', $category_id);
    $this->db->delete('tbl_category');
}

}

1 个答案:

答案 0 :(得分:1)

执行此操作的正确方法是redirect();像这样:

    $this->session->set_flashdata('message', 'Category was deleted');
    redirect('category', 'refresh');

然后在类别控制器上:

   if ($this->session->flashdata('message')) {
      //show the message to confirm
   }

最后,如果你想要javascript确认:所以当用户点击时,它会要求确认,然后如果用户点击正常则删除。当行已被删除时,您要求确认。

  <td><a onclick="return confirm('are you sure?')" href="<?=base_url()?>category/remove_category/<?=$row->category_id?>">Delete</a></td>