等到多种功能,这可能会或可能不会叫AJAX内部,有完整的jQuery的?能不、这可、或可、多种

2023-09-10 22:12:45 作者:对不起,不爱了

我目前确认的几个输入客户方。当用户提交表单,我要检查的值的形式输入,然后做一些事情,一旦所有的检查完成

I am currently validating a few inputs clientside. When the user submits the form, I want to check the values for the form inputs, and then do something once all the checks are complete

$('form').submit(function() {
    var input1 = $('form #input1');
    var input2 = $('form #input2');

    //validate both input values
    validate_input(input1);
    validate_input(input2);

    //wait until all validation complete to execute code here

    return false;
});

下面,将validate_input功能将检查的输入值。如果通过初步检查(如字符长度),那么它将使一个AJAX请求作进一步的验证(例如,如果用户名是采取检查)。事情是这样的:

Here, the "validate_input" function will check the input value. If it passes the initial checks (such as character length), then it will make an AJAX request for further validation (ex. checking if username is taken). Something like this:

function validate_input(input){
    value=input.val();
    if (value.length<4){
        //code to execute if input is too short
    }
    else {
        $.ajax({             
            type: 'get',
            url: check_input_url,
            data: input.serialize(),
            success: function(data){
                if (data=="invalid") {
                    //code to execute if invalid
                } else {
                    //code to execute if valid
                }
            }
        });
    }
}

我目前使用jQuery.when()和.done()函数,但做()函数不会等到所有的validate_input功能都完全完成(包括AJAX回调从validate_input调用)

I am currently using jQuery.when() and .done() functions, but the done() function does not wait until all the validate_input functions are completely done (including AJAX callbacks called from validate_input)

$.when(
    validate_input(input1),
    validate_input(input2)
).done(function(){
    //code here
});

我怎么会等到所有的validate_input功能齐全(有任何可能的AJAX回调结束),执行进一步的code过吗?

How would I wait until all the validate_input functions are complete (finished with any possible AJAX callbacks), before executing further code?

推荐答案

我不明白你 validate_input 函数返回任何东西。如果你要等待,你需要返回一个承诺,让你不及格未定义 $。当()

I don't see you validate_input function return anything. If you want to wait, you need to return a promise, so that you don't pass undefined to $.when():

function validate_input(input){
    var value=input.val();
    if (value.length<4){
        return …; //code to execute if input is too short
    } else {
        return $.ajax({
 //     ^^^^^^
            …
        });
    }
}