Javascript 按ID阻止jQuery中的表单提交
我正在使用jqueryajax函数检查jquerychange函数上数据库中是否存在用户电子邮件。在Ajax响应中,有两种可能存在用户电子邮件或不存在用户电子邮件。如果存在,则显示错误消息。现在我想防止表单在Ajax响应错误时提交Javascript 按ID阻止jQuery中的表单提交,javascript,jquery,ajax,forms,validation,Javascript,Jquery,Ajax,Forms,Validation,我正在使用jqueryajax函数检查jquerychange函数上数据库中是否存在用户电子邮件。在Ajax响应中,有两种可能存在用户电子邮件或不存在用户电子邮件。如果存在,则显示错误消息。现在我想防止表单在Ajax响应错误时提交 jQuery("#userEmail").change(function(){ //my code goes here if(result == 'False'){ //prevent form here } else
jQuery("#userEmail").change(function(){
//my code goes here
if(result == 'False'){
//prevent form here
}
else {
// else condition goes here
}
});
使用e.preventDefault()阻止表单提交
jQuery("#userEmail").change(function(e){
if(result == 'False'){
e.preventDefault();
}
else {
}
});
您需要使用提交事件处理程序:
jQuery("#userEmail").closest("form").submit(function(event){
var $email = jQuery("#userEmail", this);
//the email field is not `this`, but `$email` now.
//your code goes here
if(result == 'False'){
event.preventDefault();
}
else {
// else condition goes here
}
});
如果需要,您仍然可以将其他行为附加到更改事件。重要的是对提交事件执行
event.preventDefault()
。您可以放置一个全局变量,如
emailValidated = false
等等
jQuery("#userEmail").change(function(){
//my code goes here
if(result == 'False'){
emailValidated = false;
}
else {
// else condition goes here
emailValidated = true;
}
});
然后在表单提交上检查emailValidated
变量的值
$(form).submit(function(){
if(emailValidated) {
this.submit();
}
else {
return false;
}
})
这样做: var结果
$.ajax({
url: url,
// Put all the other configuration here
success: function(data){
if(data == something) // replace something with the server response
result = true; // Means that the user cannot submit the form
},
});
$('#formID').submit(function(){
if(result){
alert('Email already exists.');
return false;
}
});
- 步骤如下:
- 从Jquery中的输入字段获取用户传递的电子邮件值
- 将该数据发布到PHP查询文件中,并在jquery的“success:function(data)”函数上获取响应数据
- 在页面上显示该数据
将条件放入ajax成功函数中