Home  >  Article  >  php教程  >  Ajax submission method of Yii2.0 ActiveForm component

Ajax submission method of Yii2.0 ActiveForm component

黄舟
黄舟Original
2017-01-03 09:40:061410browse

How does ActiveForm submit asynchronously?

1. First configure the following attributes in the ActiveForm of the views layer

),           //此处为请求地址 Url用法查看手册
    'enableAjaxValidation' => true,
        'validationUrl' => Url::to(['post/validate']),     //数据异步校验
]);

2.配置好表单属性之后,在控制器中添加对应的方法

validateUrl对应的方法

//该方法是异步校验字段,输入框失去焦点之后自动会自动请求改地址
public function actionValidate(){
    $model = new PostModel();
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {        
        Yii::$app->response->format = Response::FORMAT_JSON;        
        return ActiveForm::validate($model);
    }
}

action对应的方法

//该方法是数据保存方法
public function actionSave()
{
    $model = new PostCatModel();
    if ($model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ['status' => $model->save()];
    }        
}

In addition, you also need to write a submitted js

[code=php;toolbar:false">//此处点击按钮提交数据的jquery
$('.btn').click(function () {
$.ajax({
url: "/post/save.html",
type: "POST",
dataType: "json",
data: $('form').serialize(),
success: function(Data) {
if(Data.status)
alert('保存成功');
else
alert('保存失败')
},
error: function() {
alert('网络错误!');
}
});
return false;
});

Note: the corresponding in actionSave The namespace must be added, otherwise an error will be reported

For example, Response and ActiveForm

use yiiwebResponse;
use yiiootstrapActiveForm;[/code]

The above is the asynchronous submission method corresponding to ActiveForm

Above It is the ajax submission method content of Yii2.0 ActiveForm component. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn