包含jQuery的$。员额函数(返回值)功能员额、函数、返回值、功能

2023-09-10 16:59:52 作者:凉忆

据我所知,AJAX是异步的,而所有这一切。但是,我有以下的code:

I understand that AJAX is asynchronous, and all that. But I have the following code:

function doesUsernameExist(element)
{
    // Check via AJAX (POST) if username already exists in the database
    var funcReturned = null;
    $.post(
        '_ajax_checkexist.php',
        {
            var: 'username',
            value: element.value
        },
        function(data) {
            funcReturned = (data.toLowerCase() == 'exists');
        },
        'data'
    );
    return funcReturned;
}

我理解的为什么函数没有返回值正常,但我能作为一种变通方法使用?这是有效性的插件,这需要通过的 doesUsernameExist 的函数返回一个布尔值。我不能这样做具有$。员额功能改变某些HTML元素通常的解决方法。它需要返回true / false来的 doesUsernameExist 的。

I understand why the function isn't returning a value properly, but what can I use as a workaround? This is for the Validity plugin, which requires a boolean returned by the doesUsernameExist function. I can't do the usual workaround of having the $.post function alter some HTML element. It needs to return true/false to doesUsernameExist.

我可以使用什么样的解决办法呢?我被这个难住了。

What kind of workaround can I use? I'm stumped by this.

推荐答案

如果这是为了进行验证,你会发现的 jquery.validate插件及其 远程规则 是完全适合您想要达到的目的。

If this is for validation purposes you will find that the jquery.validate plugin and its remote rule are perfectly adapted for what you are trying to achieve.

所以,而不是写, doesUsernameExist 功能和担心AJAX以及怎样的 asynchronousness 的返回值,你会写验证规则的形式(这实际上是行使=>专注于业务的最终目标,离开管道,以插件):

So, instead of writing doesUsernameExist functions and worrying about asynchronousness of AJAX and how to return values you will write validation rules for your form (which in fact is the final goal of the exercise => focus on the business and leave the plumbing to plugins):

$('#id_of_some_form').validate({
    rules: {
        password: {
            required: true
        },
        username: { 
            remote: '_ajax_checkexist.php'
        }
    }
});