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

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

问题描述

我正在处理我的最新项目的验证脚本,其中一个要求是它检查用户输入的值是否在数据库中,如果不是,则返回一个错误。

  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) {
var $ this = $(this);
var valueLength = jQuery.trim($ this.val())length;
var inputValue = jQuery.trim ());
var errorID = $ this.attr('name')+_err;
var errorPrepend =< div class ='rf_error'id ='+ errorID + >;
var errorAppend =< / div>;
var errorMsg =;

/ * =========== ======================
更多有效的报价这里
================ ============ * /

if($ this.is('。rf_GrpCode')&&!hasError)
{
$ .get(inc / scripts / formHandle.php,{GrpCode:inputValue,type:groupCode},function(data){
if(!data.GrpCode)
{
hasError = true;
errorMsg =您输入的代码无效。

}
},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);

返回错误;
}

$('#registerButton')。bind('click',function(){
if($('#formElem')。 )){
$ .confirm({
'title':'Ooops!',
'message':'您输入的某些信息无效,请返回步骤a修改标记的字段',
'buttons':{
'OK':{
'class':'blue',
'action':function ){}
}
}
});
return false;
}
});

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



我可以理解为什么它不工作,因为这些变量被设置在函数其余部分的范围之外。不幸的是,这是根据我的知识,以及如何让这些变量被错误处理部分在结尾处识别的损失。



Hope



任何帮助都非常感谢,



问题是 get 只是执行AJAX get请求的一个快捷方式。

AJAX是异步的,因此在检查变量后请求会返回。你在这里有几个选择。通常我不鼓励阻塞在ajax调用(某种失败的目的),但如果这是发生在提交,那么它可能是有意义的。



您可以将 get 更改为 ajax code> async:false 。这将等待请求完成后再继续。



如果您有多个此类调用需要等待,您应该查看 http://api.jquery.com/jQuery.when/ ,这将允许请求并行运行,但仍然等待所有完成,然后继续前进。


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;
    }   
});

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.

Hope that makes sense,

Any help is greatly appreciated, thanks,

Lyndon

解决方案

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.

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

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