【问题标题】:Yii 2, Submit form using AjaxYii 2、使用Ajax提交表单
【发布时间】:2016-05-03 23:42:08
【问题描述】:

我是 Yii 的新手,如果有任何帮助,我将不胜感激。 我用表单渲染视图:

public function actionCreate()
{    
     return $this->render('create');       
}

查看:

<form id="myform" action="/test/web/index.php?r=form/preorder" method="post">
    <input type="text" id="form-firstname" name="Form[firstName]" required maxlength="50">                    
    <input type="text" id="form-lastname" name="Form[lastName]" required maxlength="50">
    <input name="send" type="submit" value="Отправить">
</form>

我在表单中使用纯 html 而不是 Yii 扩展,因为我只需要一个带有 html/javascript 的前端。在后端我可以使用 Yii。

现在,我尝试使用 ajax 提交表单:

 $(document).ready(function(){      
$("body").on('beforeSubmit', 'form#myform', function(e){       
      var form = $(this);
      $.ajax({
            url    : form.attr('action'),
            type   : 'POST',
            data   : form.serialize(),
            success: function (response) 
            {                  
               console.log(response);
            },
            error  : function () 
            {
                console.log('internal server error');
            }
        });
    return false;

  });
});

表单控制器:

public function actionPreorder(){

     if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $res = array(
                'body'    => $_POST,
                'success' => true,
            );
            //also I need to save to db
            return $res;
     }
}

问题是当我提交表单时,它重定向到新页面preorder,我看不到我发布的数据。我不确定我做错了什么。

【问题讨论】:

  • 请说明您使用纯html的原因?因为使用 AngularJs 或类似的东西?否则最好使用带有 AJAX 验证的 ActiveForm 小部件。
  • if(Yii::$app-&gt;request-&gt;isAjax) 总是假的,因为你没有使用正确的 yii ajax 调用。在它之前检查你会得到发布的数据。
  • 删除if(Yii::$app-&gt;request-&gt;isAjax)。然后它会工作。
  • 是的,我得到了结果,但为什么它显示在新页面上?
  • @arogachev,我将使用 jquery 验证。原因是表单会放在不支持 Yii 的网站上。后端将在单独的服务器上。

标签: php jquery ajax yii yii2


【解决方案1】:

好的,所以解决方案是从表单中删除操作:

<form id="myform" action="" method="post">

js:

$("#myform").submit( function(e){
      var form = $(this);
      $.ajax({
            url    : '/megogo/web/index.php?r=form/preorder',
            type   : 'POST',
            data   : form.serialize(),
            success: function (response) 
            {                  
               console.log(response);
            },
            error  : function (e) 
            {
                console.log(e);
            }
        });
    return false;        
  })

【讨论】:

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