JQuery ajax post函数在javascript结束时执行

时间:2015-05-06 09:17:52

标签: javascript jquery ajax post

我在验证用户名是否已被使用时遇到问题。我试图使用jquery的“post”方法找出用户名是否已经存在。但是在执行此函数时,脚本始终跳转到函数的末尾,并在执行“post”命令之前首先执行脚本的其余部分。能否请您查看我的代码并帮助我?

$("#submit").click(function () {

    var username = document.getElementById("username").value;
    var email = document.getElementById("email").value;
    var passwort = document.getElementById("passwort").value;
    var passwort2 = document.getElementById("passwort2").value;
    var validate = false;

    checkUsername();

    if (validate == true) {
        $.post("Login/register.php", {

            username: username,
            email: email,
            passwort: passwort,
            passwort2: passwort2,
        }, function (info) {
            $("#errorBox").empty();
            $("#errorBox").html(info);
        });

    } else {
        $('#register').submit(function () {
            return false;
        });
    }

    function checkUsername() {
        username = document.getElementById("username").value;
        // username = replaceUmlauts(username);
        if (username.length > 0) {
            document.getElementById("username").style.borderColor = "";
            // document.getElementById("errorBox").innerHTML =
            // "";
            validate = true;
            checkAvailability();
            return false;
        } else {
            document.getElementById("username").style.borderColor = "red";
            document.getElementById("errorBox").innerHTML = "Username muss länger als ein Zeichen sein";
            // alert('Username must be longer than one sign');
            validate = false;
            return false;
        }
    }

    function checkAvailability() {
        $.post(
            "Login/checkusername.php", {
                username: username
            },
            function (result) {
                // if the result is 1
                if (result == 1) {
                    // show that the username is
                    // available
                    document
                        .getElementById("errorBox").innerHTML = "";
                    return false;
                } else {
                    // show that the username is NOT
                    // available
                    document
                        .getElementById("errorBox").innerHTML = "Username nicht verfuegbar";
                    document
                        .getElementById("username").style.borderColor = "red";
                    validate = false;
                    return false;
                }
            });

    }
    return false;

});

编辑:我的HTML代码:

<form id="register" >
<div id='registerpopup'>
	<div class='close'></div>
	<span class='ecs_tooltip'>Schließen mit ESC<span class='arrow'></span></span>
	<div id='popup_content'> <!--your content start-->
		<table border=0 cellspacing=10 cellpadding=20 align=center>
		<div id="errorBox"></div>
			<tr>
			
				<th>
					<p style="margin-top: 20px; margin-right: 5px">Username:</p>
					<p style="margin-top: 18px; margin-right: 5px">E-Mail:<p>
					<p style="margin-top: 16px; margin-right: 5px">Passwort:</p>
					<p style="margin-top: 16px; margin-right: 5px">Passwort wdhl.:</p>
				</th>
				<th>
					<p style="margin-top: 20px"><input id="username" name="username"  type='text' size='30' maxlength='30' ><br></p>
					<p><input id="email" name="email" type='text' size='30' maxlength='30'><br></p>
					<p><input id="passwort" name="passwort"  type='password' size='30' maxlength='30' ><br></p>
					<p><input id="passwort2" name ="passwort2" type='password' size='30' maxlength='30'><br></p>
				</th>
			</tr>
		</table>
		<table border=0 cellspacing=10 cellpadding=20 align=center>
			<tr>
				<th>
					<button id="submit" class="submit" type="submit"  style="margin-top: 30px"> Registrieren </button>
				</th>
			</tr>
		</table>
	</div>
</div>
</form>
<script type="text/javascript" src ="js/checkregister.js"></script>

<div class='loader'></div>
<div id='backgroundPopup'></div>

我尝试将("#submit")更改为document.getElementById("submit")以使我的代码“更干净”,但似乎无效。

2 个答案:

答案 0 :(得分:0)

您的变量validate存在范围问题,我建议您使用函数checkUsername()

if (username.length > 0) {
    document.getElementById("username").style.borderColor = "";
    // document.getElementById("errorBox").innerHTML =
    // "";
    return checkAvailability();
} else {
    document.getElementById("username").style.borderColor = "red";
    document.getElementById("errorBox").innerHTML = "Username muss länger als ein Zeichen sein";
    // alert('Username must be longer than one sign');
    return false;
}

,这在您的函数checkAvailability()

if (result == 1) {
    // show that the username is
    // available
    document.getElementById("errorBox").innerHTML = "";
    return true;
} else {
    // show that the username is NOT
    // available
    document.getElementById("errorBox").innerHTML = "Username nicht verfuegbar";
    document.getElementById("username").style.borderColor = "red";
    return false;
}
在主函数中的if语句之前

var validate = checkUsername();

编辑:这段代码很脏,你应该选择和#34;旧学校JS&#34;比如document.getElementById或jQuery(例如:$('#myId')),但不建议使用两者

答案 1 :(得分:0)

我没有足够的时间来清理它,但这将是一个良好的开端。请注意,我仅将$.post("/echo/html/", {用于演示目的,并对实际行进行了评论,因为它不会在小提琴中起作用。修改代码以满足您的需求。

演示@ Fiddle

$("#register").on("submit", function (evt) {

    evt.preventDefault();
    var $username = $("#username");
    var email = $.trim($("#email").val());
    var passwort = $.trim($("#passwort").val());
    var passwort2 = $.trim($("#passwort2").val());
    var $errorBox = $("#errorBox");
    var isUser = checkUsername();

    if (isUser) {
        checkAvailability();
    }

    function checkUsername() {
        var usernameVal = $.trim($username.val());
        if (usernameVal.length > 0) {
            $username.css({borderColor: "none"});
            return true;
        } else {
            $username.css({borderColor: "red"});
            $errorBox.html("Username muss länger als ein Zeichen sein");
        }
        return false;
    }

    function checkAvailability() {
        //$.post("Login/checkusername.php", {
        $.post("/echo/html/", {
            "username": $.trim($username.val())
        }, function (result) {
            // if the result is 1
            if (result == 1) {
                register().done(function() {
                    $errorBox.append("<p>Hurray!</p>");
                });
            } else {
                // show that the username is NOT
                // available
                $errorBox.html("Username nicht verfuegbar");
                $username.css({borderColor: "blue"});
                return;
            }
        });
    }

    function register() {
        //return $.post("Login/register.php", {
        return $.post("/echo/html/", {
            username: $.trim($username.val()),
            email: email,
            passwort: passwort,
            passwort2: passwort2,
        }, function (info) {
            $errorBox.html(info);
        });
    }
});