我通过jquery在模态和句柄表单提交中呈现表单。如果服务器返回表单,我会在模态中重新显示表单,以向用户显示表单错误。如果在服务器上验证了表单,则服务器将在内部重新安装并向用户返回成功页面。
这是通过这个小脚本(简化版)完成的:
function submitItemModalFormBind(url){
//bind the form. prevent default behavior and submit form via ajax instead
$('#ajax_form_modal_result').find(":submit").click(function(ev){
var button = ev.target;
var the_form = jQuery(this).parents("form");
var data = the_form.serialize();
data = data + "&" + button.name + "=" + button.value;
$.ajax({
type: "POST",
url: url,
data: data,
success:function(response, textStatus, jqXHR){
var form = $("#ajax_form_modal_result_div", response);
//form is returned if it is not valid. update modal with returned form
//change this "if" to check for a specific return code which should be set in the view
if (form.html()) {
//update modal div
$('#ajax_form_modal_result_div').html(form);
$("#itemFormModal").modal('show');
//rebind the form
submitItemModalFormBind(url);
}
//form is not returned if form submission succeeded
else{
//update the entire document with the response received
document.open();
document.write(response);
document.close();
$("#itemFormModal").modal('hide');
}
},
error: function (request, status, error) {
if (request.status == 0){
//status == 0 = server is unreachable or access denied
modalBody = $('#itemFormModal').find('.modal-body');
errorMessage = "<div class=\"alert alert-error\"><button class=\"close\" data-dismiss=\"alert\">x</button>Due to connection problems we could not process your request.. Please try again later. </br> ";
errorMessage = errorMessage + "If the problem persists check your internet connection and contact your system administrator.</div>" ;
modalBody.prepend(errorMessage);
};
}
});
return false;
});
}
在大多数情况下,这似乎工作得很好。然而,它可能不是最好的方法和 它与这个脚本一起工作不正常:
$(document).ready(function() {
form_bind_update();
form_bind_hide();
$("#id_project").select2({ width: 'resolve' });
$("#id_year").select2({ width: 'resolve' });
$("#id_month").select2({ width: 'resolve' });
$("#id_purchase_order_membership").select2({ width: 'resolve' });
$("#id_action").select2({ width: 'resolve' });
});
文档的第一次加载工作正常。但是当通过document.write()函数加载这些数据时,$(“id_project”)的选择崩溃了。似乎document.ready()在document.write()完成之前被触发。
有关如何更好地处理此用例的任何建议吗?