yii ajax提交表格

时间:2012-12-22 10:27:44

标签: ajax yii

控制器:

public function actionCreate() {
    $model = new SiteWidget;
    if (isset($_POST['SiteWidget'])) {
        $model -> attributes = $_POST['SiteWidget'];
        if ($model -> validate()) {
            if ($model -> save())
            {
                return 'OK';
            }       
        }
    }
    $this -> render('create', array('model' => $model, ));
}

视图:

<div class="form">  
    <?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'site-widget-form',
        'enableAjaxValidation'=>false,
        'htmlOptions'=>array(
                         'onsubmit'=>"return false;",
                         'onkeypress'=>" if(event.keyCode == 13){ send(); } "
                                 ),
    )); ?>

    <p class="note">
        Fields with <span class="required">*</span> are required.
    </p>

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

    <div class="row">
        <?php echo $form -> labelEx($model, 'title'); ?>
        <?php echo $form -> textField($model, 'title', array('size' => 60, 'maxlength' => 256)); ?>
        <?php echo $form -> error($model, 'title'); ?>
    </div>

    <div class="row">
        <?php echo $form -> labelEx($model, 'type'); 
            echo $form -> dropDownList($model, 'type',  SiteWidget::getConstants('W_', 'SiteWidget'));
            echo $form -> error($model, 'type'); ?>
    </div>
    <div class="row">
        <?php echo $form -> labelEx($model, 'status'); ?>
        <?php echo $form -> checkBox($model, 'status'); ?>
        <?php echo $form -> error($model, 'status'); ?>
    </div>
    <div class="row buttons">
        <?php echo CHtml::submitButton($model -> isNewRecord ? 'Create' : 'Save',array('onclick'=>'send();')); ?>
    </div>
    <?php $this -> endWidget(); ?>
</div>

<script language="JavaScript">
function send(){
    var data=$("#site-widget-form").serialize();

      $.ajax({
           type: 'POST',
            url: '<?php echo Yii::app()->createAbsoluteUrl("siteWidget/create"); ?>',
            data:data,
            success:function(data){
                        alert(data);
                      },
           error: function(data) {
                 alert("Error occured.please try again");
            },
          dataType:'html'
      });
}
</script>

为什么ajax不起作用? 哪里我搞错了?

3 个答案:

答案 0 :(得分:0)

<强>解决方案:

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'site-widget-form',
    'enableAjaxValidation'=>true,
    'htmlOptions'=>array(
                     'onsubmit'=>"return false;",
                     'onkeypress'=>" if(event.keyCode == 13){ send(); } "
                             ),
)); ?>

查看更多ajax submition button with valiation here

答案 1 :(得分:-1)

数据应该是一个JavaScript对象,也许是serialize()生成问题? 这是jQuery - AJAX article with working example:)

答案 2 :(得分:-1)

尝试使用Yii ajaxSubmitButton