Javascript 使用JQuery$.post进行验证
我有一个关于异步调用的问题。我试图做的是验证给定的“代码”是否有效。刷新页面不是一个选项 简而言之:Javascript 使用JQuery$.post进行验证,javascript,jquery,ajax,validation,Javascript,Jquery,Ajax,Validation,我有一个关于异步调用的问题。我试图做的是验证给定的“代码”是否有效。刷新页面不是一个选项 简而言之: 我需要根据服务器的回复将变量设置为true或false。 该调用是通过使用ajax完成的。 ajax($.post)请求处理来自服务器的回复,从而将变量设置为true或false。 然后,变量的值将用作该函数的返回值(true或false)。问题是,只有在ajax完成后才返回。ajax的异步行为阻止了这一点,而挂起浏览器并没有完成 验证通过使用函数完成(它将在if中使用) if的外观如下所示:
我需要根据服务器的回复将变量设置为true或false。
该调用是通过使用ajax完成的。
ajax($.post)请求处理来自服务器的回复,从而将变量设置为true或false。
然后,变量的值将用作该函数的返回值(true或false)。
问题是,只有在ajax完成后才返回。ajax的异步行为阻止了这一点,而挂起浏览器并没有完成 验证通过使用函数完成(它将在if中使用) if的外观如下所示:
if(codeGiven()) {
// Code ok. Continue to process
} else { msgCodeInvalid(); }
函数code给定
如下
function codeGiven(toChk) {
var codeOK = false; // default answer
if(toChk) { // only perform call if toChk is not "" of undefined
$.post(
"validate.aspx", // server script
{ code: toChk }, // value
function(data) { // function
if(data == "true") {
codeOK = true; // when true => return will be true
} else {
codeOK = false; // when false => return will be false
}
}
);
}
return codeOK; // will be false by default but true when the code is OK
}
aspx将使用发布的“代码”,并将其与我数据库中的其他代码进行匹配。如果找到匹配项,则回答为“true”。否则,答案将为“假”
因为ajax调用($.post)是异步的,所以结果总是错误的
除了我用setInterval(我知道的一种肮脏的方法)的想法之外,还有什么建议可以帮助我摆脱这个困境吗?在邮局里的回信不起作用
有什么想法吗
提前谢谢
最终解决方案
我开始意识到我可以把我的全部逻辑放在$.post中
因此,基本上,我的逻辑如下(警告,这是一个深树结构):
签入函数的回调或承诺,例如:
function checkCodeGiven(toChk) {
return $.post("validate.aspx", { code: toChk });
}
然后是这样的:
checkCodeGiven(someVar).then(function(data) {
if(data == "true") {
// do whatever you wanted to do for true
} else {
// do whatever you wanted to do for false
}
});
你可以:
. 在ajax的success函数中调用所需的函数或
. 延迟器方法:多次调用需要if(codeGiven)的部分,延迟约100ms,因此您可以确定它为false或在一次调用中变为true,请更换此部分
if(codeGiven()) {
// Code ok. Continue to process
} else { msgCodeInvalid(); }
使用codeGiven();延迟器(0)编码>并对其进行解释
function Delayer(counter) {
if (codeOK) {
// Code ok. Continue to process
} else if (counter <10) { //not sure if it may become true later
setTimeout(Delayer, 100, counter++);} //call after 0.1 sec
else {
msgCodeInvalid(); // no hope to be true
}
}
功能延迟器(计数器){
如果(代码OK){
//代码正常。继续处理
}else if(counter)您不能这样做。我知道我的第一种思考方式不起作用,因为异步行为。我考虑使用setInterval()解决它(在timeoutCount!=过期时保持循环&&!postExec。然后在postExec==true时执行代码),但后来我意识到我可以在回调中无冲突地阻塞所有代码。Tunnel vision是一件坏事,逃避它的唯一方法是将项目扔到一边,然后重新开始。或者,更好的是,使用承诺。setTimeout将挂起浏览器,这是我不愿意做的事情。无论如何,感谢您的建议,但是我设法在没有计时器的情况下解决了这个问题。我没有尝试过这个方法,但第二天早上我找到了解决问题的方法。睡眠可以对某人的大脑产生奇妙的影响。我决定把我所有的逻辑都放在$post的回调中。它不会干扰其他部分,所以它起作用了。
function Delayer(counter) {
if (codeOK) {
// Code ok. Continue to process
} else if (counter <10) { //not sure if it may become true later
setTimeout(Delayer, 100, counter++);} //call after 0.1 sec
else {
msgCodeInvalid(); // no hope to be true
}
}