[英]jquery - javascript variable not holding value
I'm using this code to submit a form to a php script: 我正在使用此代码向php脚本提交表单:
var valid = 'true';
$(document).ready(function(){
$("#contact").submit(function(){
$.post("process.php",
$("#contact").serialize(),
function(data){
if(data.email_check == 'invalid'){
valid = 'false'; //<---not set!
$("#email1").addClass('missing');
$("#message_ajax")
.html("<div class='errorMessage'>Sorry is NOT a valid e-mail address. Try again.</div>");
} else {
$("#message_ajax")
.html("<div class='errorMessage'>YES! this is A valid e-mail address. DO NOT Try again.</div>");
}
}, "json"
);
if(valid == 'true'){
$("#contact").hide();
}
return false;
});
});
I know the script is returning the 'invalid' value because the div and css are updated as expected, but the 'valid' variable never gets set to 'false'. 我知道脚本会返回“无效”值,因为div和css已按预期更新,但“有效”变量从未设置为“假”。 Thinking it was a scope issue I have moved the declaration and if statement around with no joy. 认为这是一个范围问题,所以我不高兴地搬走了声明和if声明。
Possible related problem - I'm using firebug to step through the code, but it only stops at my breakpoint the first time the code is executed, and never again, but I can submit the form any number of times and it always responds as expected - valid or invalid. 可能相关的问题-我正在使用Firebug逐步遍历代码,但是它只会在第一次执行代码时在断点处停止,并且永远不会再出现,但是我可以提交该表单多次,并且它总是会按预期方式响应-有效或无效。 As you can see, I'm very new to jQuery. 如您所见,我对jQuery非常陌生。
You're mixing synchronous and asynchronous code here. 您在这里混合同步和异步代码。
if(valid == 'true'){
$("#contact").hide();
}
return false;
This code ^^^ runs before the callback function(data)
is ever called. 此代码^^^在调用回调function(data)
之前运行。
Basically what's happening is this: 基本上是这样的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.