Php yii2,使用Ajax提交表单
我是Yii的新手,非常感谢您的帮助。 我以以下形式呈现视图:Php yii2,使用Ajax提交表单,php,jquery,ajax,yii,yii2,Php,Jquery,Ajax,Yii,Yii2,我是Yii的新手,非常感谢您的帮助。 我以以下形式呈现视图: public function actionCreate() { return $this->render('create'); } 视图: FormController: public function actionPreorder(){ if (Yii::$app->request->isAjax) { Yii::$app->respon
public function actionCreate()
{
return $this->render('create');
}
视图:
FormController:
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
,而我看不到发布的数据。我不确定我做错了什么。好的,所以解决方案是从表单中删除操作:
<form id="myform" action="" method="post">
请指定使用纯html的原因?因为使用AngularJs或类似的东西?否则,最好使用带有AJAX验证的
ActiveForm
小部件。if(Yii::$app->request->isAjax)
始终为false,因为您没有使用正确的yiiAjax调用。检查后,您将获得发布的数据。如果(Yii::$app->request->isAjax)删除。然后它会工作。是的,我得到了结果,但为什么它会显示在新页面上?@arogachev,我将使用jquery验证。原因是表格将放在不支持Yii的网站上。后端将位于单独的服务器上。
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;
}
}
<form id="myform" action="" method="post">
$("#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;
})