【发布时间】:2015-05-12 20:51:21
【问题描述】:
我有一个关于异步调用的问题。我尝试做的是验证给定的“代码”是否有效。刷新页面不是一种选择。
简而言之:
我需要根据服务器的回复将变量设置为 true 或 false。
该调用是通过使用 ajax 完成的。
ajax ($.post) 请求处理来自服务器的回复,从而将变量设置为 true 或 false。
然后变量的值将用作该函数的返回值,true 或 false。
问题是仅在 ajax 完成后才返回。 ajax 的异步行为阻止了这种情况,并且没有完成挂起浏览器。
验证是通过使用一个函数来完成的(它将在 if 中使用)。
if 如下所示:
if(codeGiven()) {
// Code ok. Continue to process
} else { msgCodeInvalid(); }
函数codeGiven如下
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 将使用发布的“代码”并将其与我数据库中的其他代码进行匹配。如果找到匹配项,则回复将为“真”。如果不是,则回复为“假”。
因为 ajax 调用 ($.post) 是异步的,所以结果总是错误的。
除了我的 setInterval 想法(我知道的一种肮脏的方法)之外,还有什么关于如何破解我的方法的建议吗?帖子内的返回无效。
有什么想法吗?
提前致谢
最终解决方案
我意识到我可以将我的整个逻辑放在 $.post 中。
所以基本上,我的逻辑如下(警告,这是一个深度树结构):
if(myvar) { // if pid not empty
$.post( // start validation
"validator.aspx", // server side validation script
{ code : myvar }, // data to be passed to the server
function(data, status) { // execute when post happend
if(data == "true") { // if answer from server == "true"
/*
assign variables
apply other logic
process effects
...
*/
} else { /* if answer from server == "false" => error: invalid code given */ }
}
).error( /* error: validator did a boom boom. We're sorry :( */ );
} else { /* error: please enter a code */ }
【问题讨论】:
-
我知道由于异步行为,我的第一种思维方式行不通。我想过用 setInterval() 来解决这个问题(在 timeoutCount != expired && !postExec 时继续循环。然后在 postExec == true 时执行代码),但后来我意识到我可以把我所有的代码都塞进没有冲突的回调。隧道视野是一件坏事,唯一摆脱它的方法就是把项目放在一边,然后带着新的想法回来。
-
或者,更好的是,使用 Promise。
标签: javascript jquery ajax validation