Yii2中AJAX提交表单并处理验证错误的关键是:控制器用Json::encode返回含errors的JSON,前端用yiiActiveForm('updateAttribute')更新错误提示。需禁用默认提交、传递CSRF令牌、匹配属性名格式。

Yii2 中使用 AJAX 提交表单并获取后端验证错误的 JSON 数据,关键在于正确配置模型验证、控制器响应格式,以及前端正确处理返回结果。默认情况下 Yii2 的 ActiveForm 会自动支持 AJAX 验证(如失去焦点时),但手动提交时需自行控制流程。
控制器中返回标准 JSON 验证错误
在 Action 中接收 POST 数据,调用 $model->load() 和 $model->validate(),若失败则返回包含 errors 的 JSON:
public function actionCreate()
{
$model = new Post();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->save();
return Json::encode(['success' => true, 'message' => '保存成功']);
} else {
// 返回验证错误,格式为 ['attribute' => ['错误1', '错误2']]
return Json::encode(['success' => false, 'errors' => $model->getErrors()]);
}
}
前端 AJAX 提交与错误渲染
禁用 ActiveForm 默认提交,用 jQuery 发起请求,并将 errors 显示在对应字段下方:
- 确保表单
id与 JS 中选择器一致(如#post-form) - 使用
$.post()提交,检查响应中的errors字段 - 遍历 errors 对象,用
$form.find("[name='Post[title]']")定位输入框,调用yiiActiveForm('updateAttribute', ...)触发错误显示 - 或手动清空旧错误、插入新
<div class="help-block error">xxx</div>
保持 ActiveForm 的内置验证机制兼容
若希望复用 ActiveForm 的样式和交互逻辑(如错误高亮、提示位置),推荐调用其内部方法更新状态:
$.post($(this).attr('action'), $(this).serialize())
.done(function(res) {
var data = JSON.parse(res);
if (!data.success) {
var form = $('#post-form');
form.data('yiiActiveForm').submitting = false;
$.each(data.errors, function(attribute, messages) {
form.yiiActiveForm('updateAttribute', 'Post-' + attribute, messages);
});
}
});
注意点与常见问题
- 控制器中不要用
return $this->renderAjax()直接返回视图,那不是纯 JSON;要用Json::encode()或Response::format = Response::FORMAT_JSON - 确保请求头
Content-Type: application/x-www-form-urlencoded(表单序列化默认满足) - 如果模型属性名含方括号(如
Post[title]),JS 中需转义或按 ActiveForm 生成的 ID(如Post-title)匹配 - 开启 CSRF 验证时,记得在 AJAX 请求中带上
X-CSRF-Token头或 post 数据中加_csrf字段


















