Javascript错误的警报顺序 [英] Javascript wrong alert order

查看:62
本文介绍了Javascript错误的警报顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的javascript调用:

I have a javascript call like this:

usernameTest('queijo');
alert('a');

函数usernameTest()正在工作,并且在调试时会警告字符串"t"或"f".

The function usernameTest() is working and, for debugging, it alerts the string "t" or "f".

为什么,当我加载此页面时,显示的第一个警报是"a",并且仅在"t"或"f"之后? (顺便说一句,jQuery也已加载到页面中.)

Why, when I load this page, the first alert shown is "a" and only after "t" or "f"? (Btw, jQuery is loaded into the page too.)

源代码:

function usernameTest(username) {
    var unReg = /^[0-9a-zA-Z_]{1,20}$/;
    if(!unReg.test(username))
        return false;
    $.ajax({
        type : 'POST',
        url : 'checkuser.php',
        data : 'username=' + username,
        cache : false,
        success : function(response) {
            if(response == 1) {
                alert('f');
                return false;
            } else {
                alert('t');
                return true;
            }
        }
    });
}

我已经知道问题是调用AJAX.现在,新的主要问题是另一个. 我这样称呼它(在适当的位置,而不是用于调试的代码);

I already know the problem is that is calls AJAX. The new main question is now another. I'm calling it like that (in the proper place, not the code for debugging);

if(!usernameTest(argument))
    //do something

我该怎么做?

推荐答案

您可以将函数作为参数传递给usernameTest,以根据所使用的代码的状态更改所要执行的操作系统.否则,您可以直接在if语句中编写代码.

You can pass the function as a parameter to usernameTest to do what you'd like if the code that is to be used may change based on the state of the system. Otherwise, you can just write the code in the if statement directly.

function usernameTest(username, onFailure) {
    // code here...

    $.ajax({
        // ajax setup here...
        success : function(response) {
            if(response == 1) {
                //...
            } else if (typeof(onFailure) === 'function' ) {
                onFailure();
            }
        }
    });
}

var name = 'Bob';
var onFailure = function() {
    // do something
};

usernameTest(name, onFailure);

另外,当您提出问题时,请尝试具体说明,除非不清楚或需要详细说明,否则请勿更改问题.如果某人回答了原始问题,则他/她应获得荣誉,其他问题应单独提出.

Also, please try to be specific when you ask your questions and don't change the question unless it is unclear or needs to be elaborated on. If someone has answered the original question, he/she should get credit and other questions should be asked separately.

这篇关于Javascript错误的警报顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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