[英]Validation using JQuery $.post
我有一個關於異步調用的問題。 我想做的是驗證給定的“代碼”是否有效。 刷新頁面不是一種選擇。
簡而言之:
我需要根據服務器的回復將變量設置為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將使用發布的“代碼”,並將其與數據庫中的其他代碼匹配。 如果找到匹配項,則答復為“ true”。 如果不是,則答復為“假”。
因為ajax調用($ .post)是異步的,所以結果將始終為false。
除了我的想法與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 */ }
請檢查函數的回調或承諾,例如:
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的成功函數中調用您想要的函數
要么
。 延遲器方法:多次調用需要if(codeGiven)的部分,延遲大約100ms,以便確保它是錯誤的或一次調用就變為真,請替換此部分
if(codeGiven()) {
// Code ok. Continue to process
} else { msgCodeInvalid(); }
使用codeGiven();Delayer(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
}
}
加上codeOK應該在全球范圍內發布
希望這對您有用編輯只是澄清了一點
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.