简陋的自动保存

yii2 自动保存

	控制器

	<?php

namespace frontend\controllers;
use Yii;


class SaveController extends \yii\web\Controller
{
	public $enableCsrfValidation = false;
	//显示首页	
	public function actionIndex(){
		return $this->render('index');
	}
	//添加显示
	public function actionInsert()
	{
		$content = Yii::$app->request->post('content');
		if($content == ''){
			$this->redirect('index.php?r=save/index');
		}
		$time = date('Y-m-d H:i:s',time());
		$save = Yii::$app->db;
		$command = $save->createCommand("insert into save values(null,'$content','$time')")->execute();
		$id = Yii::$app->db->getLastInsertID();//获得刚插入数据的id
		//echo $id;die;
		$data = $save->createCommand("select * from save where id='$id'")->queryOne();
		//print_r($data);
		return $this->render('show',['data'=>$data]);
	}
	//修改
	public function actionUpd()
	{
		$id = Yii::$app->request->post('id');
		$content = Yii::$app->request->post('content');
		$time = date('Y-m-d H:i:s',time());
		$save = Yii::$app->db;
		$save->createCommand("update save set content='$content',time='$time' where id='$id'")->execute();
		$data = $save->createCommand("select * from save where id='$id'")->queryOne();
		return $this->render('show',['data'=>$data]);
	}
	
}

	视图层1
	
<h1>文章编辑</h1>
<h4><a href="<?php echo Yii::$app->urlManager->createUrl(['save/index']) ?>">返回首页</a></h4>
<form action="index.php?r=save/insert" method='post' >
	<TEXTAREA rows="5" cols="20" onblur='add()' name='content' ></TEXTAREA>
</form>

<script>
	function add(){
		setInterval(function(){
			$('form').submit()
		},5000);
	}
</script>


	视图层2

<h1>文章编辑</h1>
<h4><a href="<?php echo Yii::$app->urlManager->createUrl(['save/index']) ?>">返回首页</a></h4>
<h6>本地自动保存时间为:<?php echo $data['time'] ?></h6>
<form action="index.php?r=save/upd" method='post' >
	<input type='hidden' name='id' value="<?php echo $data['id'] ?>"/>
	<TEXTAREA rows="5" cols="20" onblur='add()' name='content' ><?php echo $data['content'] ?></TEXTAREA>
</form>

<script>
	function add(){
		setInterval(function(){
			$('form').submit()
		},5000);
	}
</script>


posted on 2016-04-07 18:54  *孤独的夜行者*  阅读(171)  评论(0编辑  收藏  举报

导航