Javascript document.ready和ajax表单提交时间
我以一种模式呈现表单,并通过jquery处理表单提交。如果服务器返回表单,我将在模式中重新显示表单,以向用户显示表单错误。如果表单在服务器上验证,服务器将在内部重新执行,并将成功页面返回给用户 这是通过以下小脚本简化版本完成的:Javascript document.ready和ajax表单提交时间,javascript,jquery,ajax,form-submit,Javascript,Jquery,Ajax,Form Submit,我以一种模式呈现表单,并通过jquery处理表单提交。如果服务器返回表单,我将在模式中重新显示表单,以向用户显示表单错误。如果表单在服务器上验证,服务器将在内部重新执行,并将成功页面返回给用户 这是通过以下小脚本简化版本完成的: function submitItemModalFormBind(url){ //bind the form. prevent default behavior and submit form via ajax instead $('
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.write函数加载此数据时,$id_项目的选择会崩溃。似乎document.ready是在document.write完成之前触发的
有没有关于如何更好地处理这个用例的建议 读一读,写一写;应该避免。你知道什么更好用吗?是的,document.write几乎总是一种不好的做法。这里的选项在某种程度上取决于是否可以更改响应表单提交的服务器代码。如果你只能返回一个“完整”的HTML页面,那么也许你可以取出你需要的HTML,替换现有的表单,而不是重写整个文档。好吧,嗯,我想我必须重新考虑整个方法。
$(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' });
});