执行插入操作后返回列表页如何使点击刷新不重复插入?
在首页读取数据库内容并显示,然后使用添加按钮添加内容,添加完成后返回新闻列表页。在新闻列表页点击浏览器的刷新按钮,会继续执行插入操作。控制器cnews.php:
<?php
header('content-type:text/html; charset=utf-8');
class cnews extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('news_model');
}
public function index(){
$data['news'] = $this->news_model->read_news();
$this->load->view('news_view',$data);
}
public function add_news(){
$this->load->helper("form");
$this->load->library("form_validation");
//set_rules()包含三个参数,第一个是输入域的名称,第二个是错误信息的名称,第三个是错误信息的规则,这里的规则是输入内容的文本域必填
$this->form_validation->set_rules("title","Title","required");
$this->form_validation->set_rules("content","Content","required");
//如果表单验证没有成功,则显示表单;如果成功,则并且通过了验证,则会调用数据模型
if($this->form_validation->run() === false){
$this->load->view('add_news');
}else{
$this->news_model->add_news();//执行添加操作
$data['news'] = $this->news_model->read_news();//读取添加后的所有数据
$this->load->view('news_view',$data);//将数据传给模板并加载
}
}
}
?>
模型news_model.php:
<?php
class News_Model extends CI_Model{
public function __construct(){
$this->load->database();
}
//读取新闻纪录
public function read_news(){
$query = $this->db->get('news');
return $query->result_array();
}
//向数据库中插入新的新闻纪录
public function add_news(){
$this->load->helper('url');
//URL辅助函数url_title(),
$slug = url_title($this->input->post('title'),'dash',TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug'=>$slug,
'text' => $this->input->post('content')
);
return $this->db->insert('news',$data);
}
}
?>
视图news_view.php:
<html>
<head>
<title></title>
<style type="text/css">
div{width:100px;height:50px;border:1px solid blue;margin:10px 0;}
</style>
</head>
<body>
<table width="600" align="center" border="1" cellspacing="0">
<tr>
<th>id</th><th>title</th><th>slug</th><th>content</th>
</tr>
<?php foreach($news as $news_con):?>
<tr>
<td><?php echo $news_con['id']; ?></td>
<td><?php echo $news_con['title']; ?></td>
<td><?php echo $news_con['slug']; ?></td>
<td><?php echo $news_con['text']; ?></td>
</tr>
<?phpendforeach; ?>
</table>
<a >添加新闻</a>
</body>
</html>
首页(新闻列表页)截图如下:https://segmentfault.com/img/bVKGp1?w=1021&h=314
点击添加新闻按钮并且添加成功后返回的页面截图:
https://segmentfault.com/img/bVKGqf?w=1113&h=343
问题:
1,请问添加成功返回后如何能去掉url末尾的add_news?
2,请问如何设置可以使点击浏览器刷新按钮后不会进行重复的插入操作?
在add_news()方法里,添加成功后重定向下方法就可以了,redirect("cnews/");把这行代码替换掉cnews.php中的29和30行。 xgdd1987 发表于 2017-3-15 15:48
在add_news()方法里,添加成功后重定向下方法就可以了,redirect("cnews/");把这行代码替换掉cnews.php中的 ...
谢谢你,我按照你给我思路改好了。十分感谢:loveliness: 丁老头 发表于 2017-3-15 15:58
谢谢你,我按照你给我思路改好了。十分感谢
这是个经典的重复提交问题,你应该思考为什么 redirect 就不会重复提交了。
页:
[1]