yii ajax提交表单

yii可以很方便的实现ajax的表单提交,生成的_from表单,只需要添加如下红色的选项

<div class="form">



<?php $form=$this->beginWidget('CActiveForm', array(

    'id'=>'sand-test-form',

    // Please note: When you enable ajax validation, make sure the corresponding

    // controller action is handling ajax validation correctly.

    // There is a call to performAjaxValidation() commented in generated controller code.

    // See class documentation of CActiveForm for details on this.

    'enableAjaxValidation'=>true,

    'clientOptions' => array(

        'validateOnSubmit' => true,

        'afterValidate'=>'js:function(form,data,hasError){

                        if(!hasError){

                                $.ajax({

                                        "type":"POST",

                                        "url":"create",

                                        "data":$("#sand-test-form").serialize(),

                                        "success":function(data){

                                            alert("success");

                                        },

                                        });

                                }

                        }'

    ),

)); ?>



    <p>字段带<span class="required">*</span> 的为必填项.</p>

    <?php echo $form->errorSummary($model); ?>



    <div class="row">

        <?php echo $form->labelEx($model,'sid'); ?>

        <?php echo $form->textField($model,'sid'); ?>

        <?php echo $form->error($model,'sid'); ?>

    </div>



    <div class="row">

        <?php echo $form->labelEx($model,'name'); ?>

        <?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>255)); ?>

        <?php echo $form->error($model,'name'); ?>

    </div>



    <div class="row buttons">

        <?php echo CHtml::submitButton($model->isNewRecord ? '新增' : '更新'); ?>

    </div>



<?php $this->endWidget(); ?>



</div><!-- form -->

其中"data":$("#sand-test-form").serialize(),可以获取整个表单的值。在控制器里不需要做任何的更改就可以实现ajax的提交表单。

如果在表单中有个图片的选项该怎么来实现呢?参考文章http://www.yiiframework.com/extension/lcswfupload#hh1,这篇文章可以很清楚的实现图片的ajax上传,图片上传以后通过ajax返回来图片名或路径,将这个路径给一个表单的蕴藏域,这样表单

的图片路径就可以实现ajax来上传了。

你可能感兴趣的:(Ajax)