yii2中使用jquery作全选,反选,批删(练习)
控制器层中
namespace frontend\controllers; use frontend\models\Topic; use Yii;
use yii\data\Pagination;
public function actionTopic_show() { //获取此班级的评论 $request=Yii::$app->request; $cid=$request->get('cid'); // $topic=new Topic(); // $arr=$topic->show_topic($cid); $topic=new Topic(); $data = $topic->find()->andWhere(['cid'=>$cid]); //这写要显示的数据 //实例化分页类,带上参数(总条数,每页显示条数) $pages = new Pagination(['totalCount' =>$data->count(),'pageSize'=>'4']); // var_dump($arr);die; $model = $data->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('topic_show',['arr'=>$data,'m'=>$model,'pages'=>$pages]); } //批量删除 public function actionAll_del() { $request=Yii::$app->request; $tid=$request->get('str'); //传入model批删 $topic=new Topic(); $res=$topic->all_del($tid); var_dump($res); }
模型层中
使用gii创建就可以了
视图层中
<?PHP use yii\widgets\LinkPager; //使用分页 use yii\widgets\ActiveForm; use yii\helpers\Url; use yii\helpers\Html; ?> <script src="jquery-1.9.1.min.js"></script> <table> <tr> <th>标题</th> <th>作者</th> <th>时间</th> <th>内容</th> </tr> <?php foreach($m as $key=>$value): ?> <tr> <td><input type="checkbox" name="box1[]" value="<?= $value['tid'] ?>"></td> <td><?= $value['title'] ?></td> <td><?= $value['t_name'] ?></td> <td><?= date("Y-m-d H:i:s",$value['time']) ?></td> <td><?= $value['content'] ?></td> </tr> <?php endforeach; ?> <tr> <td><button id="all_true">全选</button></td> <td><button id="all_false">全不选</button></td> <td><button id="all_delete">批删</button></td> </tr> <script> //全选 $(function(){ //全选 $('#all_true').click(function () { $("input[name='box1[]']").each(function () { $(this).prop('checked',true); }) }) //全不选 $('#all_false').click(function () { $("input[name='box1[]']").each(function () { $(this).prop('checked',false); }) }) //批删 $('#all_delete').click(function () { var str=''; //取到选中的值并移除 $("input[name='box1[]']:checked").each(function () { str+=','+$(this).val(); $(this).parent().parent().remove(); }) str=str.substr(1); // alert(str); //传入后台批量删除 var url="http://localhost/day10.21/frontend/web/index.php?r=show/all_del" $.get(url,{str:str}) }) }) </script> </table> <?= LinkPager::widget([ 'pagination' => $pages, 'nextPageLabel'=>'下一页', 'prevPageLabel'=>'上一页', 'lastPageLabel'=>'尾页', 'firstPageLabel'=>'首页', ]); ?>