0

控制器:

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不起作用?我在哪里做错了?

4

3 回答 3

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 提交按钮

于 2013-09-27T15:28:04.343 回答
-1

数据应该是一个 JavaScript 对象,也许 serialize() 产生问题?这是带有工作示例的 jQuery - AJAX 文章:)

于 2012-12-22T12:32:34.447 回答
-1

尝试使用 Yii ajaxSubmitButton

于 2013-11-06T08:34:08.403 回答