控制器:
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 不起作用? 我哪里弄错了?
解决方案:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'site-widget-form',
'enableAjaxValidation'=>true,
'htmlOptions'=>array(
'onsubmit'=>"return false;",
'onkeypress'=>" if(event.keyCode == 13){ send(); } "
),
)); ?>
查看更多ajax 提交按钮,这里有验证
Data 应该是一个 JavaScript 对象,也许 serialize() 会产生问题? 这是 jQuery - AJAX 文章和工作示例 :)
尝试使用 Yii ajaxSubmitButton