JQuery:将 $.get() 回调返回到外部作用域 [英] JQuery: Return $.get() callback to outer scope

查看:20
本文介绍了JQuery:将 $.get() 回调返回到外部作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的最新项目编写此验证脚本,其中一项要求是检查用户输入的值是否在数据库中,如果不是,则返回错误.

I'm working on this validation script for my latest project, and one of the requirements is that it checks if the value that the user enters is in the database, and if it isn't it returns an error.

function validateSteps(){
    var FormErrors = false;
    for(var i = 1; i < fieldsetCount; ++i){
        var error = validateStep(i);
        if(error == -1)
            FormErrors = true;
    }
    $('#formElem').data('errors',FormErrors);   
}

function validateStep(step){
    if(step == fieldsetCount) return;

    var error = 1;
    var hasError = false;
    $('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
        var $this       = $(this);
        var valueLength = jQuery.trim($this.val()).length;
        var inputValue = jQuery.trim($this.val());
        var errorID = $this.attr('name') + "_err";
        var errorPrepend = "<div class='rf_error' id='" + errorID +"'>";
        var errorAppend = "</div>";
        var errorMsg = "";

        /* =================================
         MORE VALIDATION STATEMENTS HERE
         ============================ */

        if($this.is('.rf_GrpCode') && !hasError)
        {
            $.get("inc/scripts/formHandle.php", { GrpCode: inputValue, type: "groupCode" }, function(data) {
                if(!data.GrpCode)
                {
                    hasError = true;
                    errorMsg = "The code you have entered is invalid.";

                }
            }, "json");
        }

        if(hasError)
        {
            $this.css('background-color','#FFEDEF');
            //alert("Has error: " + errorID);
            if(errorMsg)
            {

                if($('#' + errorID).length)
                {
                    $('#' + errorID).html(errorMsg);
                }
                else
                {
                    $this.after(errorPrepend + errorMsg + errorAppend);
                }
            }
        }
        else
        {
            //alert("Has no error: " + errorID);
            $('#' + errorID).remove();
            $this.css('background-color','#FFFFFF');    
        }
    });

   var $link = $('#navigation li:nth-child(' + parseInt(step) + ') a');
    $link.parent().find('.error,.checked').remove();

    var valclass = 'checked';
    if(hasError){
        error = -1;
        valclass = 'error';
    }
    $('<span class="'+valclass+'"></span>').insertAfter($link);

    return error;
}

$('#registerButton').bind('click',function(){
    if($('#formElem').data('errors')){
        $.confirm({
            'title'     : 'Ooops!',
            'message'   : 'It appears some of the information you have entered is invalid. Please go back through the steps a amend the marked fields.',
            'buttons'   : {
                'OK'    : {
                    'class' : 'blue',
                    'action': function(){}
                }
            }
        });
        return false;
    }   
});

$.get() 请求本身工作正常,如果数据库中没有该值的实例,它将进入 if 语句.但是,一旦涉及到错误处理部分,它就不会选择我在 if 语句中设置的变量.

The $.get() request itself works fine and will get through into the if statement if there is no instance of the value in the database. However once it comes to the error handling section it's not picking up the variables that I set within the if statement.

我可以理解为什么它不起作用,因为这些变量被设置在函数其余部分的范围之外.不幸的是,就我所知,这就是我所知道的,并且我不知道如何让最后的错误处理部分识别这些变量.

I can understand why it's not working, because those variables are being set out of the scope of the rest of the function. Unfortunately this is as far as my knowledge goes, and am at a loss as to how to get those variables to be recognised by the error handeling section at the end.

希望这是有道理的,

非常感谢任何帮助,谢谢,

Any help is greatly appreciated, thanks,

林登

推荐答案

问题在于 get 只是执行 AJAX get 请求的快捷方式.AJAX 是异步的,因此在您检查变量后返回请求.你有几个选择.通常我不鼓励阻塞 ajax 调用(有点违背目的),但如果这是在提交时发生的,那么它可能是有道理的.

The issue is that get is simply a shortcut for doing an AJAX get request. AJAX is asynchronous, so the request is returning after you've checked the variable. You have a few options here. Normally I don't encourage blocking on an ajax call (kind of defeats the purpose), but if this is happening on submit, then it may make sense.

您可以将 get 更改为 ajax 并设置 async: false.这将在继续之前等待请求完成.

You can change get to ajax and set async: false. This will wait for the request to finish before moving on.

如果你有多个这样的调用需要等待,你应该看看http://api.jquery.com/jQuery.when/ ,这将允许请求并行运行,但在继续之前仍然等待所有请求完成.

If you have multiple such calls that you need to wait for, you should have a look at http://api.jquery.com/jQuery.when/ , this will allow the requests to run in parallel, but still wait for all to complete before moving on.

这篇关于JQuery:将 $.get() 回调返回到外部作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆