我面临一个奇怪的问题,我必须通过两种方法到达表单页面:创建和编辑。从创建 URL 发布时,相同的表单可以完美运行,但每当我通过编辑或重新创建 URL 发布时,页面会自行刷新并尝试在 URL 本身上发布。
网址为: http://localhost:8000/admin/orders/create http://localhost:8000/admin/orders/create/1234
代码是:
$('#quote_form').validate({
rules: {
item: {
required: true,
},
quantity: {
required: true,
}
},
focusInvalid: true,
invalidHandler: function(form, validator) {
$('#' + validator.errorList[0].element.id).focus();
},
submitHandler: function() {
$('#newQuote').empty();
let dataArray = $('#quote_form').serializeArray();
let item = $('#item').val();
let customerValue = '';
if ($('#customer').val().length !== 0 && $('#customer').val() !== undefined) {
customerValue = $('#customer').val();
} else if ($('#customer_id').val().length !== 0 && $('#customer_id').val() !== undefined) {
customerValue = $('#customer_id').val();
}
dataArray.push({
name: 'customer',
value: customerValue
});
$.ajax({
url: ADMIN_AJAX_URL + "orders/create-order-session",
method: 'post',
data: dataArray,
success: function(response) {
let result = JSON.parse(response);
if (result.html != '') {
clearForm($("#quote_form"));
$('#newQuote').append(result.html);
} else {
$('.error_text').html(result.message);
$('.error_row').show();
}
}
});
}
});
我尝试通过提交按钮和表单验证等方式发布,但没有无聊的结果。
要防止默认的表单提交行为,请在您的submitHandler中传递event.preventDefault()。submitHandler函数接收表单参数,因此您应该将其传递到$(form).serializeArray()而不是使用$('#quote_form' ).serializeArray().
$('#quote_form').validate({
rules: {
item: {
required: true,
},
quantity: {
required: true,
}
},
focusInvalid: true,
invalidHandler: function(form, validator) {
$('#' + validator.errorList[0].element.id).focus();
},
submitHandler: function(form, event) {
event.preventDefault();
$('#newQuote').empty();
let dataArray = $(form).serializeArray();
let item = $('#item').val();
let customerValue = '';
if ($('#customer').val().length !== 0 && $('#customer').val() !== undefined) {
customerValue = $('#customer').val();
} else if ($('#customer_id').val().length !== 0 && $('#customer_id').val() !== undefined) {
customerValue = $('#customer_id').val();
}
dataArray.push({
name: 'customer',
value: customerValue
});
$.ajax({
url: ADMIN_AJAX_URL + "orders/create-order-session",
method: 'post',
data: dataArray,
success: function(response) {
let result = JSON.parse(response);
if (result.html != '') {
clearForm($("#quote_form"));
$('#newQuote').append(result.html);
} else {
$('.error_text').html(result.message);
$('.error_row').show();
}
}
});
}
});