JQuery: Return $.get() callback to outer scope

后端 未结 4 838
生来不讨喜
生来不讨喜 2020-12-22 07:00

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 i

相关标签:
4条回答
  • 2020-12-22 07:24

    The problem is, that your ajax call is asynchron. So your condition check if(hasError) { will be executed before your success handler even set the value for hasError. You can't execute code directly after you initiated your ajax call. Instead have all other code within your success listener.

    if($this.is('.rf_GrpCode') && !hasError)
    {
        $.get("inc/scripts/formHandle.php", { GrpCode: inputValue, type: "groupCode" }, function(data) {
            if(!data.GrpCode)
            {
                errorMsg = "The code you have entered is invalid.";
    
    
                $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');    
            }
        }, "json");
    }
    
    0 讨论(0)
  • 2020-12-22 07:27

    The $.get() request is asynchronous. You will only have hasError set after the response comes in, which is a lot later than when you're checking it.

    0 讨论(0)
  • 2020-12-22 07:33

    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.

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

    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.

    0 讨论(0)
  • 2020-12-22 07:34

    The get function is asynchronous. You process the results probably before an answer has arrived.

    0 讨论(0)
提交回复
热议问题