gpt4 book ai didi

javascript - e.PreventDefault 和 ajx 提交不能一起工作 [return true] 不起作用

转载 作者:行者123 更新时间:2023-12-01 01:03:10 24 4
gpt4 key购买 nike

我有一个功能来检查电子邮件是否存在,但我只想在电子邮件不存在时提交表单

所以我写了以下函数:

$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");

var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {

var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});

现在,如果它返回 true,我也无法提交表单。请帮忙。 我看到这个问题和答案e.preventDefault doesn't stop form from submitting 。但没有效果

Notes

即使我尝试过

  if(response.status=='true') { $("#form-1").submit(); } .

但这也不起作用

最佳答案

return语句在表单提交之前返回

if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}

建议

你在想这个,错误的方式,让PHP来处理检查并在后端插入。

第一个解决方案

在你的 PHP 中做类似的事情

$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}

在你的JS中

$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");

var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {

var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});

第二种解决方案

将表单保存在变量中。

$("#form-1").on("submit",function(e){
e.preventDefault();

const form = $(this); // get the current form

var given_email=document.getElementById("email");

var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {

var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

关于javascript - e.PreventDefault 和 ajx 提交不能一起工作 [return true] 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com