繁体   English   中英

使用JQuery $ .post进行验证

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM