私は ajax を初めて使用し、JSP で Ajax と JavaScript を使用して gmail タイプのユーザー名の可用性チェックを作成しようとしています。
私のコードはユーザー名の可用性チェックにはうまく機能しますが、ユーザー名が使用できない場合にフォームの送信を停止できません。
ユーザー名の可用性を確認するには、各文字をチェックする onkeyup() を使用しましたが、フォームの送信を防ぐには、フォーム タグで onsubmit() を使用しました。
実行フロー チェックのために、次のコードでアラート ステートメントを使用しました。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
function returnFunction(str)
{
    alert("1");
    var flag = new Boolean(false);
    usernameValidation(str);
    alert("2");
    function usernameValidation(str)
    {
        alert("3");
        var xmlHttpRequest;
        if(window.XMLHttpRequest)
        {
            alert("4");
            xmlHttpRequest = new XMLHttpRequest();
            alert("5");
        }
        else
        {
            alert("6");
            xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttpRequest.onreadystatechange = function()
        {
            alert("7");
            if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
            {
                alert("8");
                if(xmlHttpRequest.responseText=="available")
                {
                    flag=new Boolean(true);
                    alert("9 flag:"+flag);
                    document.getElementById("myDiv").innerHTML="username is available";
                }
                else
                {
                    flag=new Boolean(false);
                    alert("10 flag:"+flag);
                    document.getElementById("myDiv").innerHTML="username is already taken";
                }
            }
        };
        xmlHttpRequest.open("POST", "UsernameCheck", true);
        xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");        
        xmlHttpRequest.send("uname="+str);
    };
    alert("before return flag is:"+flag);
    return flag;
};
    function formValidation(){
        if(returnFunction(document.f1.username.value))
            {
              alert("caught flage:true");
              return true;
            }
        else{
            alert("caught flage:false");
            return false;
        }
    }
</script>
</head>
<body>
<form method="post" action="register"  name="f1" onsubmit="return formValidation()">
    User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="returnFunction(this.value)"></div>
            <span id="myDiv" style="color: red"></span>
            <input type="submit" value="register">
            </form>
</body>
</html>