【问题标题】:Yii php ajax Undefined variable: modelYii php ajax 未定义变量:模型
【发布时间】:2014-02-07 17:04:59
【问题描述】:

我还在为 ajax 表单和 Yii 苦苦挣扎。 我收到错误未定义变量:模型。我的表单是由另一个视图渲染部分由另一个视图渲染部分本身。

这里有详细信息

在我的 POST 控制器中

public function actionViewComment()
    {   
        $post=$this->loadModel();
        $comment=new Comment;
        $this->renderPartial('_viewComment',array(
            'model'=>$post,
            'comment'=>$comment,
        ));

}

_viewcomment.php 调用commment/_form.php

<?php $this->renderPartial('/comment/_form',array(
            'model'=>$comment,
        )); ?>

在 _form.php 中,变量 $model 是可访问的 有一个按钮在单击时调用 jquery 函数 send()

函数发送() {

   var data=$("#comment-form").serialize();


  $.ajax({
   type: 'POST',
    url: '<?php echo Yii::app()->createAbsoluteUrl("post/Ajax"); ?>',
   data:data,
success:function(data){
                alert("Data Saved"); 
              },
   error: function(data) { // if error occured
         alert("Error occured.please try again");
         alert(data);
    },

  dataType:'html'
  });

}

post控制器的actionAjax包含

public function actionAjax()
    {
if(isset($_POST['Comment']))
        {
           if($model->validate())
            {
               $model->save();
               return;
            }
        } 
     }

在 Ajax 操作中,我收到错误未定义变量:模型。我不明白为什么?

如果我使用 $model=new 评论;数据没有保存,因为 $model 是空的

你能解释一下吗?

通过添加

$model=new Comment;
$model->attributes = $_POST["Comment"]; 

我出现以下错误

DbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 19 tbl_comment.status may not be NULL. The SQL statement executed was: INSERT INTO 'tbl_comment' ("author", "email", "url", "content", "create_time") VALUES (:yp0, :yp1, :yp2, :yp3, :yp4) (C:\wamp\www\yii\framework\db\CDbCommand.php:358)</p><pre>#0 C:\wamp\www\yii\framework\db\ar\CActiveRecord.php(1077): CDbCommand->execute()

提前感谢您的帮助。

【问题讨论】:

    标签: php jquery ajax yii


    【解决方案1】:

    在您的actionAjax 中,您必须为Comment 创建模型对象。您没有创建 $mode,但您正在调用它们的函数。

    public function actionAjax()
        {
            if(isset($_POST['Comment']))
            {
               $model=new Comment;
               $model->attributes = $_POST["Comment"];
               if($model->validate())
                {
                   $model->save();
                   echo "saved";
                }
                else
                {
                   echo "Failed";
                }
            } 
         }
    

    【讨论】:

    • 我已经这样做了,但在这种情况下,数据没有保存。我看着萤火虫,发送的数据是空的。 @kumar_v
    • 所以你的帖子是空的?
    • 不,不是。我可以在萤火虫中看到 $_POST 等于我输入的数据 @kumar_v
    • 萤火虫中的响应仍然是空的。 @kumar_v
    • 尝试更新代码。但是你会从 ajax 得到一些响应。所以如果你失败了,那么验证失败。然后检查您的模型验证和数据
    猜你喜欢
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多