Uda*_*try 3 javascript ajax jquery
我在注册表单上触发 ajax 调用,其中我正在检查用户输入的电子邮件 ID 是否已被使用。阿贾克斯功能:
<script>
$( "#becomesignup" ).submit(function( event ) {
$.ajax({
url : 'login', // Your Servlet mapping or JSP(not suggested)
data : {"email":$("#becomeemail").val()},
type : 'GET',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
if(response == "true"){
$('#emailerrorbecome').slideDown();
$('#become-submit').prop('disabled', true);
event.preventDefault();
}else{
$('#emailerrorbecome').slideUp();
$('#become-submit').prop('disabled', false);
}
$('.black-screen').hide();
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
在上面的 ajax 函数中,如果响应为真,则电子邮件 ID 已被使用,我需要显示错误 div($('#emailerrorbecome').slideUp();) 然后阻止表单提交。但即使 event.preventDefault() 也不起作用,导致再次注册电子邮件 ID。请帮我解决一下这个。TIA
您应该以编程方式提交表单,并始终防止 jq 提交处理程序中的默认行为。例如,使用上下文并调用submit()DOM API 方法:
$("#becomesignup").submit(function(event) {
event.preventDefault(); /* prevent form submiting here */
$.ajax({
context: this, /* setting context for ajax callbacks*/
url: 'login', // Your Servlet mapping or JSP(not suggested)
data: {
"email": $("#becomeemail").val()
},
type: 'GET',
dataType: 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success: function(response) {
if (response == "true") {
$('#emailerrorbecome').slideDown();
$('#become-submit').prop('disabled', true);
$('.black-screen').hide(); /* hide it here */
} else {
$('#emailerrorbecome').slideUp();
$('#become-submit').prop('disabled', false);
this.submit(); /* 'this' refers to the FORM, and calling submit() DOM native method doesn't fire again jq handler */
}
},
error: function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
Run Code Online (Sandbox Code Playgroud)
为了解释为什么,看到昆汀的回答
你打电话preventDefault已经晚了。
执行顺序是这样的:
\n\n在阻止默认行为之前,您不能等待 HTTP 响应返回。
\n\n你要么需要总是阻止默认行为,然后在提交处理程序中使用 JS 有条件地重新提交表单,要么移动使用 Ajax 执行测试时的逻辑,以便它首先不依赖于表单提交事件(例如,输入数据后立即运行它,并准备好在 JS 完成运行之前表单可能被提交的可能性)。
\n| 归档时间: |
|
| 查看次数: |
9498 次 |
| 最近记录: |