在JSP中使用Ajax并停止表单提交的用户名可用性检查

时间:2012-12-15 08:48:38

标签: ajax validation jsp username

我是ajax的新手,我正在尝试使用JSP中的Ajax和JavaScript创建一个gmail类型的用户名可用性检查。

我的代码适用于用户名可用性检查,但是当用户名不可用时,我无法停止提交表单。

为了检查用户名可用性,我使用了onkeyup()来检查每个字符,但是为了防止我在表单标签中使用onsubmit()的表单提交。

对于执行流程检查,我在此代码中使用了alert语句:

<%@ 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>

4 个答案:

答案 0 :(得分:0)

Ajax是异步的,所以你对returnFunction的调用,不需要返回正确的标志,它总是会返回false,因为最有可能只有在方法完成后才会触发成功函数(响应)。 因此,您需要确保使用completed布尔值接收Ajax cal的响应,并持续检查它直到它为真。

<script type="text/javascript" language="javascript">
function returnFunction(str)
{
alert("1");
var flag = new Boolean(false);
var completed = 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(){
   returnFunction(username);
   while(!completed) {
   //wait for ajax response
   }
   if(flag)
        {
          alert("caught flage:true");
          return true;
        }
    else{
        alert("caught flage:false");
        return false;
    }
}
 </script>

答案 1 :(得分:0)

<%@ 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">

var flag = new Boolean(false);
function returnFunction(str)
{
alert("1");

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");
          document.f1.submit();

        }
    else{
        alert("caught flage:false");
        alert("Username chossen by u is already taken.Please choose different Username");
    }
}
</script>

</head>
<body>
<form method="post" action="register"  name="f1" >
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>

进行这样的更改它会起作用。如果有任何疑问,请知道。

答案 2 :(得分:0)

<%@ 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 getXMLHttpRequest(){
      var xmlHttpReq = false;
      // to create XMLHttpRequest object in non-Microsoft browsers
      if (window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
      } 
      else if (window.ActiveXObject) {
        try {
          // to create XMLHttpRequest object in later versions
          // of Internet Explorer
          xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (exp1) {
          try {
            // to create XMLHttpRequest object in older versions
            // of Internet Explorer
            xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (exp2) {
            xmlHttpReq = false;
          }
        }
      }
      return xmlHttpReq;
    };
    function usernameValidation(str)
    {
        if (str.length==0) 
        { 
            document.getElementById("uname").innerHTML="should not be empty";
            return false;
        }
        else if(str.length<=4)
        {
                document.getElementById("uname").innerHTML="need more than 4 charachers";
                return false;
        }
        else{
                var xmlHttpRequest = getXMLHttpRequest();
                xmlHttpRequest.onreadystatechange =function()
                {
                    if (xmlHttpRequest.readyState < 4 && xmlHttpRequest.readyState > 0)
                    {
                        document.getElementById("uname").innerHTML = "<img src='images/load.gif' alt='checking...' width=16 height=16/>";
                    }
                    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
                    {
                        if(xmlHttpRequest.responseText=="available")
                        {
                            document.getElementById("uname").innerHTML = "<img src='images/ok.png' alt='username available' width=16 height=16/>";
                            document.getElementById("uname1").innerHTML = ".";
                        }
                        else
                        {
                            document.getElementById("uname").innerHTML = "username not available";
                        }
                    }
                };
                xmlHttpRequest.open("POST", "UsernameCheck", true);
                xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                xmlHttpRequest.send("uname="+str);

            };
    };

function userSubmitValidation(){
    var msg = document.getElementById("uname1").innerHTML;  
    if(msg=='.'){
        return true;
    }
    else{
        return false;
    }
};

</script>

</head>
<body>

<form method="post" action="register"  name="f1"  onsubmit="return userSubmitValidation()">
    User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="usernameValidation(this.value)" onblur="usernameValidation(this.value)"></div>
            <span id="uname" style="color: red"></span><span id="uname1" style="color: white"></span>

            <input type="submit" value="register">
            </form>

</body>
</html>

答案 3 :(得分:0)

我也是ajax的新人,我有点想做你正在做的事情。我已经使用ajax和jsp成功检查了用户名可用性。然后我坚持的事情,即使用户名不可用,页面仍然提交后单击提交按钮。然后我用javascript来解决这个问题。我将返回的文本与之前声明的其他文本进行了比较如果检查成功,那么它将转到下一页,否则不会。有关详细信息,请查看此页面 - &gt;“Ajax based username availablity checking and then generating some username to use in jsp”。检查sample.jsp代码。在该代码中,我在名为“conditions()”的函数中执行了检查部分。在该函数中,变量“checkvalue”保存由可用性检查生成的返回文本。然后我将它与“可用”文本进行比较。如果匹配则页面将提交其他明智的。我不确定这是你想知道的,如果是,那么我的答案对你有帮助。谢谢你,祝你好运..