美文网首页
使用ajax进行异步表单验证

使用ajax进行异步表单验证

作者: 我爱铲屎 | 来源:发表于2019-07-12 22:03 被阅读0次

在传统的Web应用中,用户的身份验证是通过向服务器提供表单,服务器对表单中的用户信息进行验证,然后返回验证的结果,在这样的处理方式中,客户端必须等到服务器返回处理结果才能进行别的操作,而且在这个过程中还会刷新整个页面。
在Ajax的处理方式中,可以把用户的信息通过XMLHttpRequest对象异步发送给服务器,在服务器完成对用户身份信息的处理后,把处理结果通过XMLHttpRequest对象返回用户,以异步的方式在不刷新页面的情况下完成对用户身份的验证。

利用Ajax实现对登录数据的验证。假设正确的用户名为“张三”,正确的密码为“123456”。在用户登录的时候判断用户名和用户密码是否正确,如果正确则跳转到欢迎页面;否则,在登录页面提示错误。

表单页面login.html
<div id="loginBox">
       <span>请输入用户名:</span><input type="text" name="userName" id="userName"/><br/><br/>
       <span>请输入密码:</span><input type="password" name="userPwd" id="userPwd"/><br/><br/>
       <input type="button" value="登录" onclick="fromCheck()"/><br/><br/>
       <div id="showMsg"></div>
</div>

点击“登录”按钮时,调用fromCheck()函数使用ajax异步验证用户信息。

function fromCheck(){
  var userName = document.getElementById("userName").value;
  var userPwd = document.getElementById("userPwd").value;

  var url ="/ajax/check";  //ajax向该处发出检查用户信息的请求
  var params = "userName="+userName+"&userPwd="+userPwd;
  var method = "POST";

  sendRequest(url,method,params,callBack);
}

在fromCheck()方法中的sendRequest()方法是对ajax发送异步请求的封装。封装ajax的完整代码如下:

<script type="text/javascript">
    var xmlHttpRequest = null;
    //创建XMLHttpRequest对象
    function createXHR(){
        try{
            xmlHttpRequest = new XMLHttpRequest();
        }catch(e1){
            //兼容不同版本的IE浏览器
            var _msXmlHttp = new Array("Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.5.0",
                                       "Msxml2.XMLHTTP.4.0","Msxml2.XMLHTTP.3.0",
                                       "Msxml2.XMLHTTP","Microsoft.XMLHTTP");
            for(int i=0;i<_msXmlHttp.length;i++){
                try{
                     xmlHttpRequest = new ActiveXObject(_msXmlHttp[i]);
                     if(xmlHttpRequest!= null)break;
                }catch (e2){}
            }
        }
        if(xmlHttpRequest == null){
           alert("不能创建AJAX对象");
        }
    }
    /**
     * 发送客户端请求
     * url:请求的地址
     * method:请求的方法,GET或POST请求
     * params:传递到服务端的参数
     * callback:响应函数
     */
    function sendRequest(url,method,params,callback) {
        createXHR();
        if(!xmlHttpRequest)return false;
        xmlHttpRequest.onreadystatechange = callback;
        if(method === "GET"){
            xmlHttpRequest.open(method,url+"?"+params,true);
            xmlHttpRequest.send(null);
        }
        if(method === "POST"){
            xmlHttpRequest.open(method,url,true);
            xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xmlHttpRequest.send(params);
        }
    }
</script>

在sendRequest()方法中method有两种方式"GET"和"POST",需要注意这两种方式向服务器传递参数方式的不同。
GET请求时,参数是通过"?"拼接在url后面。

xmlHttpRequest.open(method,url+"?"+params,true);

POST请求的参数是通过send()传递的。同时,POST请求还需要指定请求头的"Content-Type"为"application/x-www-form-urlencoded",否则服务器无法接受到请求的数据。

 xmlHttpRequest.open(method,url,true);
 xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 xmlHttpRequest.send(params);

在sendRequest()方法中callback参数为响应函数,该函数为用户定义的在ajax接受到服务器的响应后要去干什么。在这个例子中,我们希望在接受到"error"的响应信息时,在登录页面中<div id="showMsg"></div>提示错误;如果接受到"success"的响应信息,就跳转到欢迎页面。callback函数的代码如下:

//ajax响应的处理函数
        function callBack() {
            if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
                var info = xmlHttpRequest.responseText;
                if(info === "error"){
                    document.getElementById("showMsg").innerText="用户名或密码错误!";
                }else{
                    //info === "success"
                    window.location.href="/ajax/welcome";//访问欢迎页面
                }
            }
        }
欢迎页面welcome.html
<body>
    <div>Login Success ! Welcome</div>
</body>
controller层

服务器端用Spring Boot写。

@Controller
@RequestMapping("ajax")
public class AjaxController {
    /**
     * 进入登录页面
     * */
    @GetMapping("/login")
    public String login(){
        return "login";
    }
    
    /**
     * 用户登录信息检查
     * */
    @RequestMapping(value = "/check",method = RequestMethod.POST)
    @ResponseBody
    public void loginCheck(HttpServletRequest request,HttpServletResponse response)
            throws IOException{

        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");

        if(!"张三".equals(userName) || !"123456".equals(userPwd)){
            out.print("error"); //  失败
        }else{
            out.print("success");   //成功
        }
    }

    /**
     * 进入欢迎页面
     * */
    @GetMapping("/welcome")
    public String welcomePage(){
        return "welcome";
    }

}
运行结果

登录成功


微信图片_20190712214630.png
微信图片_20190712214621.png

登录失败


微信图片_20190712214602.png

相关文章

网友评论

      本文标题:使用ajax进行异步表单验证

      本文链接:https://www.haomeiwen.com/subject/ortukctx.html