[英]Setting the variable in javascript function
我在将值设置为变量时遇到问题。 我的代码如下。
function fpform(){
var response_new = '';
var password_reset = "";
var fpemail = $('#frgtpwd').val();
//var fpemail = document.getElementById('frgtpwd').value;
if (fpemail == ""){
$('span#fperror').text("insert your emal address");
//document.getElementById('fperror').innerHTML = "Insert your email address";
password_reset = 'no';
} else {
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(fpemail)==false) {
$('span#fperror').text("Email address is not in valid format");
//document.getElementById('fperror').innerHTML = "Email address is not in valid format";
password_reset = 'no';
} else {
$("#loader").html('<img src="images/ajax-loader.gif" />');
$.post("forgot_password_process.php", {
email:fpemail
}, function(response){
response_new = response.trim();
}).success(function () {
if (response_new == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").empty();
password_reset = 'yes';
} else {
$("#loader").empty();
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
password_reset = 'no';
}
});
}
}
if (password_reset == "yes"){
alert(password_reset);
return true;
} else {
alert(password_reset);
return true;
}
}
最后一个if条件是检查password_reset变量是否设置为yes,并根据该变量返回true或false。 但是警报显示password_reset变量的空白值。 我似乎找不到任何问题,因为password_reset变量应该在到达最后一个if之前分配。 任何人都可以建议解决方案。
亲切的问候
$.post()
是异步的,因此当您提醒数据时,请求尚未完成。 为此,您还需要在成功回调中调用警报,以确保在尝试警报之前已拥有数据。 另一种选择是使用同步AJAX调用(尽管这很少是一个好的选择)。
更新资料
不确定为什么您的函数返回true / false,但是要使其正常工作,您必须进行同步的AJAX调用,否则外部函数将在AJAX调用完成之前返回很长一段时间,此时您不知道反应是什么。
您可能应该尝试重组代码,以使依赖于外部函数响应的代码可以通过成功回调来调用。
我要发布与Christofer相同的内容。 这是一个固定的代码示例。 只需删除最后一个代码块。
.success(function () {
if (response_new == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").empty();
password_reset = 'yes';
alert 'yes';
return true;
} else {
$("#loader").empty();
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
password_reset = 'no';
alert 'no';
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.