我环顾四周,其他类似的帖子都没有帮助我。我已经在Yii 2
和jQuery
中构建了一个基于AJAx
的表单,似乎它提交了两次表单。
我的表格:
$form = ActiveForm::begin([
'id' => 'company_form',
'ajaxDataType' => 'json',
'ajaxParam' => 'ajax',
'enableClientValidation' => false
]);
我的JS代码:
$(document).ready(function() {
/* Processes the company signup request */
$('#company_form').submit(function() {
signup('company');
return false;
});
})
function signup(type) {
var url;
// Set file to get results from..
switch (type) {
case 'company':
url = '/site/company-signup';
break;
case 'client':
url = '/site/client-signup';
break;
}
// Set parameters
var dataObject = $('#company_form').serialize();
// Run request
getAjaxData(url, dataObject, 'POST', 'json')
.done(function(response) {
//.........
})
.fail(function() {
//.....
});
// End
}
标准提交不应该因为我将return: false;
放入 javascript 代码而停止吗?
为什么提交两次?
然而,奇怪的是,这似乎只发生在第一次;如果我再次点击提交,它只会提交一次;但是如果我重新加载页面并点击提交,它会再次执行两次。
您可能需要更改代码,如下所示:
$('#company_form').submit(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
signup('company');
return false;
});
http://api.jquery.com/event.stoppropagation/
http://api.jquery.com/event.stopimmediatepropagation/
解决方案常见
接下来JS将适用于任何'enableClientValidation'
状态:
$('#company_form').on('beforeSubmit', function (e) {
signup('company');
return false;
});
https://yii2-cookbook.readthedocs.io/forms-activeform-js/#using-events