我想这个代码来处理形式:jQuery的.preventDefault()问题
//All form submissions should go through here.
$(document).on('submit', 'form', function (x) {
//x.preventDefault(); //commented out because it's not working
$.ajax({
url: $(this + '#formdestination').val(), //formdestination is a hidden field, showing where to submit the form
type: 'post',
dataType: 'json',
data: $(this).serialize(),
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
window.location = '/broken/?err=Inconsolable%20onsubmit%20ajax%20error'; //i'd like the real error here, ideally
} //end if
else {
loader($('#pagedestination').val());
//loader is a function that animates the page as it loads new content.
//#pagedestination is a hidden field that stores where the page should go when it's done.
//Yes, I know formdestination and pagedestination could be handled with the form or the backend. There are reasons that do not matter much here.
} //end else
} //end complete function
});
return false;
});
有一对夫妇的我遇到的问题。
1.)当表单被提交时,它调用这个函数。它不调用加载程序,或者如果是这样,它会被控制器的重定向覆盖。表单提交时,我需要阻止通用提交。 .preventDefault()无法正常工作(请参阅下文)。
2.)(远比#1重要)如果ajax胡扯出来,我想得到合法的错误。怎么样?
在.preventDefault() - 当我尝试它,我得到这个错误:未捕获的SyntaxError:意外的标识
感谢您的帮助。
您的x.preventDefault()在事件处理函数回调函数之外,那么您在哪里使用它? – cernunnos 2013-03-01 17:05:13
谢谢cernunnos - 事后我在错误的位置粘贴了它。我修正了这个例子。 – shubniggurath 2013-03-01 17:06:35
@shubniggurath你在这个脚本之上加载jQuery吗? – Jai 2013-03-01 17:09:25