我正在使用Bootbox作为我的模态,而我在向模式的Ajax调用中显示表单验证错误时遇到了麻烦。我的模态上的提交按钮的回调函数调用add_college函数通过Ajax提交表单。
如果存在验证错误,则会使用验证错误填充模式。问题是无论是否存在验证错误,模态都会关闭。我希望模态仅在没有验证错误时才关闭。
我知道我可以在我的按钮上的回调函数中返回false,当有验证错误没有关闭它但我无法知道是否有验证错误,因为我无法在Ajax调用中返回值,因为它是异步的。这样做的正确方法是什么?
这是我的代码:
$('#new-college-btn').click(function () {
bootbox.dialog({
title: "New College",
message:
''// <Insert long HTML form here>
,
buttons: {
add: {
label: "Add",
className: "btn btn-primary",
callback: function () {
var form_data = {
college_name: $('#college-name').val(),
college_initials: $('#college-initials').val(),
username: $('#username').val(),
password: $('#password').val(),
confirmation_password: $('#confirmation-password').val()
};
add_college(form_data);
}
},
cancel: {
label: "Cancel",
className: "btn btn-default"
}
}
}); // end bootbox dialog
});
function add_college(form_data) {
console.log(form_data);
$.ajax({
url: 'admin/add_new_college',
type: 'POST',
data: form_data,
dataType: 'JSON',
success: function (response)
{
if (response.error) { // there are form validation errors
// populate modal with validation errors here
} else {
// other data processing here
Result.success('College Successfully Added!');
}
},
error: function () {
console.log("fail");
}
});
}
答案 0 :(得分:1)
如果您想控制对话框关闭的时间,请确保您的&#34;提交&#34;按钮始终返回false。然后,在ajax函数的done()
(可能是fail()
)回调中,调用bootbox.hideAll()
关闭对话框(以及您可能已打开的任何其他对话框)。
如果您只想关闭当前对话框,请执行以下操作:
var dialog = bootbox.dialog({
/* rest of your options... */,
buttons: {
submit: {
label: "Submit",
callback: function() {
var data = [];
$.post('/url', data)
.done(function(result, status, jqxhr){
// if everything went well...
dialog.modal('hide');
})
.fail(function(jqxhr, status, error){
// etc.
});
return false;
}
}
}
});
基本上,创建一个对话框的引用,然后你可以在ajax回调中使用它。