YII2.0+默认自带Jquery消息提示插件toastr
单独引用模式:当前view视图中,引用如下:
=Html::jsFile('@web/js/plugins/toastr/toastr.min.js')?>
=Html::cssFile('@web/css/plugins/toastr/toastr.min.css')?>
全局引用模式:打开 assets/AppAsset.php 添加如下:
public $css = [
//其他引用URL
'css/plugins/toastr/toastr.min.css',
];
public $js = [
//其他引用URL
'js/plugins/toastr/toastr.min.js',
];
视图代码如下:
=Html::jsFile('@web/js/plugins/toastr/toastr.min.js')?>
=Html::cssFile('@web/css/plugins/toastr/toastr.min.css')?>
= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
[
'class' => 'yii\grid\ActionColumn',
'header' => '操作',
'options' => ['width' => '100px;'],
'template' => ' {test} ',
'buttons' => [
'test' => function ($url, $model){
return Html::a(
'A标签响应onclick事件,并且不执行href动作',
'javascript:;',
[
'onclick'=>'test(this, '.$tid.');',
'title' => Yii::t(
'app',
'A标签响应onclick事件,并且不执行href动作'
),
'class' => 'del btn btn-success btn-xs',
]
);
},
],
],
],
]); ?>
beginBlock('myjs') ?>
toastr.options = {
"closeButton": true,
"debug": true,
"progressBar": false,
"positionClass": "toast-top-right",
"showDuration": "400",
"hideDuration": "1000",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
/**
* A标签响应onclick事件,并且不执行href动作
*/
function test(_this,id) {
$.post(
'=Yii::$app->homeUrl?>test/ajax-test',
{'tid':id,'_csrf':'=Yii::$app->request->getCsrfToken();?>'},
function(result){
var res = jQuery.parseJSON(result);
if (res.code=='success') {
toastr.success(res.msg, '成功信息提示!');
} else if(res.code=='info') {
toastr.info(res.msg, '常规信息提示!');
} else if(res.code=='warning') {
toastr.warning(res.msg, '警告信息提示!');
} else if(res.code=='error') {
toastr.error(res.msg, '错误信息提示!');
}
}
);
}
endBlock() ?>
registerJs($this->blocks['myjs'], \yii\web\View::POS_END); ?>
控制器代码如下:
/**
* A标签响应onclick事件,并且不执行href动作
*/
public function actionAjaxTest(){
$request = Yii::$app->request;
$tid = $request->post('tid');
if (!$tid) {
//错误消息提示
echo json_encode(array('code' => 'error', 'msg' => '错误消息!'));
}else{
if($tid==1){
//成功消息提示
echo json_encode(array('code'=>'success','msg'=>'成功消息!'));
}else if($tid==2){
//常规消息提示
echo json_encode(array('code'=>'info','msg'=>'常规消息!'));
}else {
//警告消息提示
echo json_encode(array('code' => 'warning', 'msg' => '警告消息!'));
}
}
}