首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何让ajax更新和ajax验证在Yii2中协同工作?

如何让ajax更新和ajax验证在Yii2中协同工作?
EN

Stack Overflow用户
提问于 2021-10-10 09:49:40
回答 1查看 29关注 0票数 0

我有一个带有GridView的页面,我希望可以在不重新加载页面的情况下编辑数据。GridView结构是基本的。当我单击该按钮时,我将表单上传到模式窗口,然后跟踪表单提交事件。数据会正确更改,但ajax验证不起作用。

ActiveForm

代码语言:javascript
运行
复制
    <?php $form = ActiveForm::begin([
        'id' => 'update-form',
        'action' => Url::to(['/product/ajax-update', 'wbId' => $model->wbId]),
        'validationUrl' => Url::to(['/product/ajax-validate', 'wbId' => $model->wbId]),
        'enableAjaxValidation' => true,
        'validateOnChange' => true,
        'method' => 'post',
    ]); ?>

    <?= $form->field($model, 'wbId') ?>
    <?= $form->field($model, 'supplierArticle') ?>
    <?= $form->field($model, 'costPrice') ?>
    <?= $form->field($model, 'accountName') ?>

    <?php ActiveForm::end(); ?>

验证规则

代码语言:javascript
运行
复制
    public function rules()
    {
        return [
            [['wbId', 'supplierArticle', 'costPrice', 'createDate'], 'required'],
            [['wbId'], 'integer'],
            [['costPrice'], 'number'],
            [['createDate', 'updateDate'], 'safe'],
            [['supplierArticle'], 'string', 'max' => 100],
            [['accountName'], 'string', 'max' => 50],
            [['wbId'], 'unique'],
        ];
    }

载荷模态形式函数

代码语言:javascript
运行
复制
    public function actionLoadForm()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        if (Yii::$app->request->isAjax)
        {
            $wbId = Yii::$app->request->post('wbId');

            if ($wbId)
            {
                $product = Product::find()->where(['wbId' => $wbId])->one();

                if ($product)
                {
                    return [
                        'success' => true,
                        'render' => $this->renderPartial('parts/form', [
                            'model' => $product
                        ])
                    ];
                }
            }
        }

        return false;
    }

Ajax更新函数

代码语言:javascript
运行
复制
    public function actionAjaxUpdate($wbId)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        if (Yii::$app->request->isAjax)
        {
            /* @var $model Product */
            $model = Product::find()->where(['wbId' => $wbId])->one();

            if ($model)
            {
                if ($model->load(Yii::$app->request->post()) && $model->validate())
                {
                    if ($model->save())
                    {
                        return [
                            'success' => true
                        ];
                    }
                }
            }
        }
        
        return [
            'success'=> false
        ];
    }

Ajax验证

代码语言:javascript
运行
复制
    public function actionAjaxValidate($wbId)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        if (Yii::$app->request->isAjax)
        {
            /* @var $model Product */
            $model = Product::find()->where(['wbId' => $wbId])->one();

            if ($model->load(Yii::$app->request->post()))
            {
                return ActiveForm::validate($model);
            }
        }

        return false;
    }

Js - load表单

代码语言:javascript
运行
复制
 $(document).on('click', updateItemButton, function (e)
    {
        let wbId = $(this).closest('tr').data('key');

        $(updateModal).modal('show');

        $.ajax({
            type: "POST",
            url: "/product/load-form",
            dataType: "json",
            cache: false,
            data: {
                "wbId": wbId
            },
            success: function (response)
            {
                if (response.success)
                {
                    $(updateModal_content).html(response.render);
                }
                else
                {
                    console.log(response);
                }
            },
            error: function (response)
            {
                console.log(response);
            }
        });

        e.preventDefault();
    });

Js -提交-表单

代码语言:javascript
运行
复制
$(document).on('submit', updateModal_form, function (e)
    {
        e.preventDefault();

        let formData = $(this).serializeArray();

        $.ajax({
            type: "POST",
            url: $(this).attr('action'),
            dataType: "json",
            cache: false,
            data: formData,
            success: function (response)
            {
                console.log(response);
            },
            error: function (response)
            {
                console.log(response);
            }
        });
    });

验证事件根本不会触发。无论是在更改数据时还是在提交表单时。如果输入了不正确的数据,请求将被发送到ajax-update,服务器返回一个空响应(因为没有通过验证)。如何让ajax数据保存和ajax验证协同工作?

*我想在不使用pjax的情况下解决这个问题。

**如果不通过ajax加载表单,一切都会正常工作。显然,问题就在这里。

EN

回答 1

Stack Overflow用户

发布于 2021-10-19 10:06:12

Thx to Michal Hynčica.我只需要在呈现表单时使用renderAjax()方法而不是renderPartial()方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69514108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档