Yii2用Ajax提交模式形式

时间:2019-06-17 10:03:48

标签: yii2 yii2-basic-app

我已经成功创建了模态表单,但是我无法使用Ajax提交它。每次我单击“提交”按钮时,它都不会停留在索引页面中,而是显示控制器中的echo 1

我的控制器

public function actionCreate()
{
    $model = new Testing();

    if ($model->load(Yii::$app->request->post())) {
       if($model->save()){
            echo 1;
        }else{
            echo 0;
        }
    }else{

        return $this->renderAjax('create', [
            'model' => $model,
        ]);
    }
}

我的表格

 <div class="testing-form">

    <?php $form = ActiveForm::begin(['id' => $model->formName()]); ?>

    <?= $form->field($model, 'test')->textInput(['maxlength' => true]) ?>

    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
    </div>

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

</div>

<?php
$this->registerJS("

$('form#{$model->formName()}'.on('beforeSubmit', function(e)
{
    var \$form = $(this);
    $.post(
        \$form.attr('action'),
        \$form.serialize()
    )
        .done(function(result) {
        if(result == 1)
        {
            $(\$form).trigger('reset'); 
            $.pjax.reload({container:'#issuehrGrid'});
        }else
        {

            $('#message').html(result.message);
        }
        }).fail(function()
        {
            console.log('server error');
        })
    return false;
});"    
);     
?>

我的观点

<div class="report">
                    <h3>HR Issues</h3>
                     <?= Html::a('<span class="glyphicon glyphicon-plus"></span> Add', ['create'], ['class' => 'btn btn-success modalButton']) ?>
                    <?php Pjax::begin(['id'=>'issuehrGrid']); ?>
                    <table class="table table-bordered table-hover">
                        <tbody>
                        <?php foreach ($dataProvider->models as $hr) {
                          ?>
                          <tr>

                            <td><?=$hr->test;?></td>

                          </tr>
                          <?php } ?>     
                        </tbody>
                    </table>
                    <?php Pjax::end(); ?>
                </div>

请帮助我。

谢谢!

1 个答案:

答案 0 :(得分:1)

我怀疑它会向您显示空白页面,其中显示describe('login', () => { let getState; let dependencies; let dispatch; beforeEach(() => { // mocking out depencies using testdouble.js (mocking library, dont pay too much attention to it getState = td.function('getState'); dependencies = { fetchToken: td.function('fetchToken'), fetchUser: td.function('fetchUser'), storeItem: td.function('storeItem'), }; dispatch = td.function('dispatch'); }); test('shows a message on failure, when the token could not be retrieved', () => { // bla }); test('shows a message on failure, when the user could not be retrieved', () => { // bla }); test('logs the user in', async () => { const credentials = { username: "marco@polo.com", password: '123' }; const user = { /* some object */ } td.when(dependencies.fetchToken(credentials)).thenResolve({ access_token: 'token123' }); td.when(dependencies.fetchUser('token123')).thenResolve(user); await loginUser(credentials)(dispatch, getState, dependencies); td.verify(dispatch({ type: FETCHING })); td.verify(dispatch({ type: FETCHED })); }); }); 是因为在第一次提交后,您的Pjax网格是通过语句重新加载的

1

并重新加载您的$.pjax.reload({container:'#issuehrGrid'}); 事件不会再次绑定到表单,因为再次重新加载了表单beforeSubmit,并且当您第二次提交表单时,它只是使一个简单的表单提交并显示空白页面上包含Html的页面,则需要对pjax使用1事件,以便重新加载网格,脚本将pjax:complete事件再次绑定到表单。

此外,您的脚本中有一个语法错误,应予以修复。将脚本更改为以下

beforeSubmit

更新

也不要忘记更改控制器操作代码,并将<?php $formName = $model->formName(); $js = <<<JS $(document).on("ready pjax:complete",function(){ $('form#{$formName}').on('beforeSubmit', function(e){ var \$form = $(this); $.post( \$form.attr('action'), \$form.serialize() ).done(function(result) { if(result == 1) { $(\$form).trigger('reset'); $.pjax.reload({container:'#issuehrGrid'}); }else { $('#message').html(result.message); } }).fail(function() { console.log('server error'); }) return false; }); }); JS; $this->registerJS( $js, \yii\web\View::POS_READY ); ?> 更改为echo 1,将return 1更改为echo 0