【发布时间】: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->request->isAjax)总是假的,因为你没有使用正确的 yii ajax 调用。在它之前检查你会得到发布的数据。 -
删除
if(Yii::$app->request->isAjax)。然后它会工作。 -
是的,我得到了结果,但为什么它显示在新页面上?
-
@arogachev,我将使用 jquery 验证。原因是表单会放在不支持 Yii 的网站上。后端将在单独的服务器上。