做项目时总会碰到ajax提交的功能,特别是在做后台提交时,一般都会用模型自动生成,这个功能的使用会比较频繁,其实只要了解了流程,操作还是挺简单的,使用起来也方便。
表单部分
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?php $form = ActiveForm::begin([
'action' => [ 'save' ], //提交地址(*可省略*)
'method' => 'post' , //提交方法(*可省略默认POST*)
'id' => 'form-save' , //设置ID属性
'options' => [
'class' => 'form-horizontal' , //设置class属性
],
'enableAjaxValidation' => true,
'validationUrl' => 'validate-view' ,
]); ?>
<?php echo $form ->field( $model , 'company_name' , [ 'inputOptions' => [ 'placeholder' => '请输入商家名称' , 'class' => 'form-control' ], 'template' => '<label for="inputCompanyName" class="col-sm-1 control-label"><span class="text-red">*</span> 商家名称</label><div class="col-md-8">{input}</div><label class="col-sm-3" for="inputError">{error}</label>' ])->textInput()?>
<?=Html::submitButton( '保存' ,[ 'class' => 'btn btn-primary' ]); ?>
<?php ActiveForm:: end (); ?>
|
其中:'enableAjaxValidation' => true, 必须设置,告诉表单用ajax提交
控制器(controller)部分
控制器分两部分,一部分是效验表单的正确性,另外一部分是保存
1、效验部分
?
1
2
3
4
5
6
7
8
9
|
public function actionValidateView()
{
$model = new model();
$request = \\Yii:: $app ->getRequest();
if ( $request ->isPost && $model ->load( $request ->post())) {
\\Yii:: $app ->response->format = Response::FORMAT_JSON;
return ActiveForm::validate( $model );
}
}
|
2、保存部分
?
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public function actionSave()
{
\\Yii:: $app ->response->format = Response::FORMAT_JSON;
$params = Yii:: $app ->request->post();
$model = $this ->findModel( $params [id]);
if (Yii:: $app ->request->isPost && $model ->load( $params )) {
return [ 'success' => $model ->save()];
}
else {
return [ 'code' => 'error' ];
}
}
|
Ajax提交from表单
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
$( function (){
$(document).on( 'beforeSubmit' , 'form#form-save' , function () {
var form = $( this );
//返回错误的表单信息
if (form.find( '.has-error' ).length)
{
return false ;
}
//表单提交
$.ajax({
url : form.attr( 'action' ),
type : 'post' ,
data : form.serialize(),
success: function (response){
if (response.success){
alert( '保存成功' );
window.location.reload();
}
},
error : function (){
alert( '系统错误' );
return false ;
}
});
return false ;
});
});
|
相关文章
猜你喜欢
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 25
-
2025-05-25 13
-
2025-05-27 62
-
2025-05-29 67
-
2025-05-27 42
热门评论