【问题标题】:Yii Framework: AJAX form?Yii 框架:AJAX 形式?
【发布时间】:2011-10-02 03:27:16
【问题描述】:

好的,我需要一些看起来很简单的帮助,但我就是想不通。

我在 Yii 中有一个页面,我试图在其中嵌入一个 AJAX 表单。让我们调用页面 A。表单接受单个值,如果没问题,需要对其进行验证并将其存储到数据库中。

到目前为止,这是我想出的:

表单在视图 _form.php 中,其中包含一个 CActiveForm 和一个 ajaxSubmitButton,如下所示:

<?php echo CHtml::ajaxSubmitButton('submit', $this->createUrl('/site/something'), array('update'=>'#targetdiv'));?> 

在另一个 A 的视图中调用表单,如下所示:

<?php echo $this->renderPartial('/site/_form', array('AModel'=>$model)); //Passing some info about A ?>

在控制器的 actionSomething 中,我正在执行以下操作:

if (Yii::app()->request->isAjaxRequest) {

  $model = new AJAXForm('submit');

  if (isset($_POST['AJAXForm'])) {

    $model->attributes = $_POST['AJAXForm'];

    if ($model->validate()) {
    //When data's valid, save to DB is working fine. This part is working perfectly.
    }
    else {
      //This is the part I'm confused about and that's not working

      /*Trying to render the form to get the error messages and summary displayed
      but nothing's showing */
      $this->renderPartial('/site/_form', array('AModel'=>$model));

      Yii::app()->end();

    }
  }
}

在 Firebug 中,我确实看到当遇到错误时,响应会再次包含整个部分呈现的表单。但是,targetdiv 没有使用带有错误消息的更新表单进行更新。

我感觉我在 actionController 中做错了什么,但我不知道是什么。如果我也能看到 AJAX 提交表单的完整示例,那将会很有帮助。

谢谢!

【问题讨论】:

标签: yii ajaxform


【解决方案1】:

$model-&gt;getErrors() 会给你所有属性的所有错误

http://www.yiiframework.com/doc/api/1.1/CModel#getErrors-detail

if ($model->validate()) {
  //When data's valid, save to DB is working fine. This part is working perfectly.
  }
else {
  $errors = $model->getErrors();
  echo $errors;

  Yii::app()->end();
}

然后将其传递给ajaxSubmitButton() ajax 选项,根据 Yii 论坛上的这篇帖子:http://www.yiichina.net/forum/index.php/topic/23236-extension-how-to-display-validation-errors-comming-from-ajax-validation/

'success'=>"function(html) {
   if (html.indexOf('{')==0) {
        var e = jQuery.parseJSON(html);
        jQuery.each(e, function(key, value) {
        jQuery('#'+key+'_em_').show().html(value.toString());
        jQuery('#'+key).addClass('clsError');
        jQuery('label[for='+key+']').addClass('clsError');
   });
}

【讨论】:

    【解决方案2】:

    尝试将“dataType”添加到您的 ajaxSubmitButton 属性中,例如:

    array('type' =>'POST',
        'update' => '#targetdiv',
        'dataType' => 'html',
    ),
    

    您可能希望先尝试传回一些基本文本以进行测试——如果您只是尝试显示错误消息,则可能不需要重新呈现表单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-29
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多