Javascript确实用户存在,从ajax返回值到后期

Javascript does user exists, returning value from ajax to late?

本文关键字:返回值 ajax 用户 存在 Javascript      更新时间:2023-09-26

我有一个脚本,告诉访问者如果用户名是已经存在或不之前,他可以继续,下面你可以看到我的一部分代码;

编辑:好吧,我已经读了你们说的,并修改了它,但我仍然不让它工作:S,我的老师也不知道…

<script type="text/javascript">
jQuery(document).ready(function(){
    // Smart Wizard     
    jQuery('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
    function onNextStep(){
        validateSteps(function (next) { return next; });
    }   
    function onFinishCallback(){
        alert('Finish Clicked');
    } 
    function UsernameExist(fullname, callback)
    {
        var data = 'user='+ fullname;
        if(fullname) {
            $.ajax({
                type: "POST",
                url: "user_check.php",
                data: data,
                async: false,
                beforeSend: function(html) {
                    $("#msg_lastname").html('');
                },
                success: function(html){ 
                    $("#msg_lastname").show();
                            $("#msg_lastname").append(html);
                    if(html.search("red") != -1)
                    {
                        callback(false);
                    }
                    else
                    {
                        callback(true);
                    }
                }
            });
        }
   }
    function validateSteps(callback){
        var isStepValid = true;
        // validate step 1
        var firstname = $('#firstname').val();
       if(!firstname || (firstname.length < 3 || firstname.length > 10))
       {
            $('#msg_firstname').html('<br/><font color="red">Enter a first name, between 3 and 10 letters.</font>').show();
            isStepValid = false;
       }
       else
       {
         $('#msg_firstname').html('').hide();
       }
       var lastname = $('#lastname').val();
       if(!lastname || (lastname.length < 3 || lastname.length > 14))
       {
            $('#msg_lastname').html('<br/><font color="red">Enter a last name, between 3 and 14 letters.</font>').show();
            isStepValid = false;
       }
       else
       {
         $('#msg_lastname').html('').hide();
       }
       var gender = $('#gender').val();
       if(!gender || Number(gender) == -1)
       {
            $('#msg_gender').html('<br/><font color="red">Choose your gender!</font>').show();
            isStepValid = false;
       }
       else
       {
         $('#msg_gender').html('').hide();
       }
       var age = $('#age').val();
       if(!age || Number(age) > 90 || Number(age) < 21)
       {
            $('#msg_age').html('<br/><font color="red">Enter a age between 21 and 90.</font>').show();
            isStepValid = false;
       }
       else
       {
         $('#msg_age').html('').hide();
       }
       var pin = $('#pin').val();
       if(!pin || pin.length > 10 || pin.length < 4)
       {
            $('#msg_pin').html('<br/><font color="red">Enter a PIN between 4 and 10 numbers.</font>').show();
            isStepValid = false;
       }
       else
       {
         $('#msg_pin').html('').hide();
       }
       if (isStepValid) {
            UsernameExist(firstname + ' ' + lastname, function (exists) {
                callback( exists );
            });
        } else {
            callback( false );
        }
    }   
    jQuery('select, input:checkbox').uniform();
});
</script>

现在的问题是,当我运行这个脚本,它返回未定义,我猜是因为UsernameExist做得不够快,似乎返回UsernameExist没有等待它的某种原因…

您在运行UsernameExists之前返回它。

相反,像这样调用UsernameExists:
if (isStepValid) {
    UsernameExist(firstname + ' ' + lastname, function (exists) {
        return exists;
    });
} else {
    return false;
}

这是有效的,因为UsernameExists期望一个回调函数,并且在成功时将truefalse传递给callback()

您只需将async选项设置为false

function UsernameExist(fullname, callback) {
    var data = 'user=' + fullname;
    if (fullname) {
        $.ajax({
            type: "POST",
            url: "user_check.php",
            data: data,
            async: false,
            beforeSend: function (html) {
                $("#msg_lastname").html('');
            },
            success: function (html) {
            //your code after success
            }
        });
    }
}
jQuery.ajax
If you need synchronous requests, set this option to false

所以你需要执行你的ajax调用,直到它完全完成执行你想要的基于结果

也许你应该在jQuery加载完成后调用UsernameExist(fullname, callback)

try this:

getScript('http://code.jquery.com/jquery-1.9.1.min.js', function () {UsernameExist(fullname, callback)});

function getScript(url, callback) {
var script;
script = document.createElement("script");
script.setAttribute('language', 'javascript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
var done = false;
vObj = script.onload;
script.onload = script.onreadystatechange = function () {
    if (!done && (!this.readyState ||
            this.readyState == "loaded" || this.readyState == "complete")) {
        done = true;
        if (typeof callback === 'function')
            callback(this.ownerDocument.attributes);
    }
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);}

试试这样:

// Smart Wizard     
$('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep() {
    var isValid = validateSteps();
    alert(isValid);
}   
function onFinishCallback(){
    alert('Finish Clicked');
}
function UsernameExist(fullname)
{
    var data = 'user='+ fullname;
    var userAlreadyExists = null;
    if(fullname) {
        $.ajax({
            type: "POST",
            url: "user_check.php",
            data: data,
            async: false,
            beforeSend: function(html) {
                $("#msg_lastname").html('');
            },
            success: function(html){ 
                $("#msg_lastname").show();
                $("#msg_lastname").append(html);
                if(html.search("red") != -1)
                {
                    userAlreadyExists = false;
                }
                else
                {
                    userAlreadyExists = true;
                }
            }
        });
    }
    return userAlreadyExists;
}
function validateSteps(){
    ...
    if (isStepValid) {
        return UsernameExist(firstname + ' ' + lastname);
    } else {
        return false;
    }
}