form 表单提交时用ajax异步请求导致ajax请求结果无法接收问题

  • Post author:
  • Post category:其他


1、背景描述,有个公司内部用的小系统,不想大动干戈用太多前端框架,就用HTML5写了个登陆页面,刚开始想着用form表单提交登陆账户信息。后来因为前后端分离,并且统一用ajax调用后台服务交互数据,因此在form表单提交的方法中加了ajax异步调用后台服务验证登陆信息。

2、问题,在登陆功能测试时,偶尔出现点登陆按钮后,页面跳转并重新加载后无反应(控制台没有报错,后台服务正常),前端ajax调用成功后方法打了断点也没进入,再点登陆按钮几次又能正常登陆。

3、解决,经过测试为form表单提交并刷新页面后,ajax异步请求结果还没有接收到,导致ajax调用成功后方法没有执行。所以能感觉到页面刷新了一下(因为URL后面多了个”?”号),但没有登陆成功,也没有报错。最后去掉form表单问题解决。

登陆失败多了个”?”号

修改正确后代码:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <link rel="icon" sizes="any" mask href="favicon.ico">
    <title>登陆页面</title>
    <style>
    *{
        margin:0;
        padding:0;
    }
    body{
        margin:0 auto;
        background-color:#E7FBFA;
    }
    #loginDiv{
        margin:0 auto;
        background-color:#E7FBFA;
        background-size:1024px 567px;
        min-width:824px;
        min-height:600px;
    }
    #divForm, form{
        margin:0 auto;
        /* display:block; */
        /* border:1px solid #303a40; */
        /* padding: 200px 0 0 390px; */
        min-width:434px;
        min-height:400px;
    }
    ul{
        margin:40px auto 10px auto;
    }
    li{
        list-style:none;
        height:30px;
        text-align: center;
        margin-bottom:10px;
    }
    li span{
        display: block;
        color:#ff6633;
        font-size: 12px;
    }
    .error-border{
        border:1px solid #ff6633;
    }
    .success-border{
        border:1px solid #BBB;/*2eff37*/
    }
    .username, .password{
        padding:0 0 0 10px;
        color:#666;
        width:200px;
        height: 30px;
        /* border:1px solid #BBB; */
    }
    .username:focus, .password:focus {
        outline: none;
        border-color: #4488F9;
    }
    ::-webkit-input-placeholder { /* WebKit, Blink, Edge */    color: #BBB; font-size:14px}
    :-moz-placeholder { /* Mozilla Firefox 4 to 18 */   color: #BBB;  font-size:14px}
    ::-moz-placeholder { /* Mozilla Firefox 19+ */   color: #BBB;  font-size:14px}
    :-ms-input-placeholder { /* Internet Explorer 10-11 */   color: #BBB;  font-size:14px}
    .saveAccounts{
        margin:0 auto;
        padding:0;
        width:200px;
        height: 16px;
        font-size: 12px;
        color:#BBB;
    }
    .saveAccounts  input[type=checkbox] {
        cursor: pointer;
        position: relative;
        border:1px solid #BBB;
        background-color:rgba(0,0,0,0);
        color:#BBB;
        height: 16px;
        padding:0;
        margin:0;
        vertical-align:top;
    }
    .saveAccounts  input[type=checkbox]::after {
        position: absolute;
        top: 0;
        background-color: #fff;
        color: #fff;
        width: 14px;
        height: 14px;
        display: inline-block;
        visibility: visible;
        padding-left: 0px;
        text-align: center;
        content: ' ';
        border-radius: 2px;
        box-sizing: border-box;
        border: 1px solid #ddd;
    }
    .saveAccounts  input[type=checkbox]:checked::after {
        content: "";
        background-color: #037DF3;
        border-color: #037DF3;
        background-color: #037DF3;
    }
    .saveAccounts  input[type=checkbox]:checked::before {
        content: '';
        position: absolute;
        top: 1px;
        left: 5px;
        width: 3px;
        height: 8px;
        border: solid white;
        border-width: 0 2px 2px 0;
        transform: rotate(45deg);
        z-index: 1;
    }
    .loginTips{
        margin:0 auto;
        width:200px;
        height: 25px;
        color:#ff0000;
    }
    .submit{
        margin:0 auto;
        width:200px;
        height: 25px;
        text-align: center;
        background-color: #0066FF;
        padding:17px 0 0 0;
    }
    .submit input{
        color:#fff;
        font-size:14px;
        border-style:none;
        margin:0 auto;
        width: 200px;
        height: 25px;
        text-align: center;
        background-color:rgba(0,0,0,0);
    }
    </style>
</head>

<body>
<div id="loginDiv">
<!-- <form action=""> -->
<div id="divForm">
    <ul class='logging'>
        <li>
            <input class="username success-border" type="text" placeholder="请输入帐号" onfocus="focusFun(this)" onblur="blurFun(this)" maxlength="11">
        </li>
        <li>
            <input class="password success-border" type="password" placeholder="请输入密码">
        </li>
    </ul>
    <div class="saveAccounts">
        <input type="checkbox" id="saveInput" title="记住密码" checked="checked" onClick="saveCook()"/>&nbsp;记住密码
    </div>
    <div class="loginTips">
        <span class="loginTipsSpan"></span>
    </div>
    <div class="submit">
        <input id="submit" type="submit" value="登&nbsp;&nbsp;&nbsp;录">
    </div>
</div>
<!-- </form> -->
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    var request_url = 'http://127.0.0.1:8009/test';
    function getCookie(cname)
    {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) 
        {
            var c = ca[i].trim();
            if (c.indexOf(name)==0) return c.substring(name.length,c.length);
        }
        return "";
    }

    function setCookie(cname,cvalue,exdays){
        var d = new Date();
        d.setTime(d.getTime()+(exdays*24*60*60*1000));
        var expires = "expires="+d.toGMTString();
        document.cookie = cname+"="+cvalue+"; "+expires;
    }


    //请求数据
    function httpRequestData(url,inSendData,callBack)
    {
        //创建一个 XMLHTTPRequest 类型对象
        var xhr = null;
        if (window.XMLHttpRequest) {//标准浏览器
        xhr = new window.XMLHttpRequest;
        } else {//IE浏览器 
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.onreadystatechange = success;
        //open()方法开启请求
        xhr.open("POST", url, true); //请求的类型GET POST; true异步(默认) false同步
        //post请求要自己设置请求头
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//发送表单数据
        //xhr.setRequestHeader("Content-type", "application/json"); //发送json格式数据
        //xhr.setRequestHeader("Content-type","application/json;charset=utf-8"); //发送json格式数据
        //xhr.setRequestHeader("Content-type", "text/plain;charset=utf-8");发送纯文本
        //xhr.setRequestHeader("Content-type", "text/html;charset=utf-8");发送html文本
        //xhr.send(JSON.stringify(inSendData).replace(/\s+/g,""));
        //xhr.send(JSON.stringify(inSendData));
        xhr.send(inSendData);
        //xhr.send(null);

        function success() {
            if (xhr.readyState == 4) { //回传成功
                if(xhr.status == 200){
                    //console.info(xhr.responseText);
                    console.log('network success.');
                    callBack(xhr);
                    //return true;
                }
                else{
                    console.log("Problem retrieving XML data");
                    //return true;
                }
            }
            //else {
            //	console.log('network error.');
            //	return false;
            //}
        }
    }

    function focusFun(point){
        //触发焦点,若输入的值跟默认值一样,输入的值为空
        if(point.defaultValue == point.value){
            point.value = '';

        }
    }

    function blurFun(point){
        //失去焦点时,若值为空,则值等于默认值,也就是placeholder
        if(point.value == ''){
            point.value = point.defaultValue;
        }
    }

    function saveCook(){
        //取消记住密码,则删除
        if(!document.getElementById("saveInput").checked){
          // 删除cookie
          setCookie('un', '', 0);
          setCookie('pw', '', 0);
        }
        setCookie('cc', document.getElementById("saveInput").checked, 365);
    }

	function checkLogin(un,pwd) {
	  //var sendData = "{'login':'"+un+"','pass':'"+pwd+"'}";
	  var sendData = "login="+un+"&pass="+pwd;
	  httpRequestData(request_url + '/login/getUserInfo',sendData,addInfo);
	};

    function submitForm(){
        if(document.getElementById("saveInput").checked){
            setCookie('un', $('.username').val(),365);
            setCookie('pw', $('.password').val(),365);
        }
        setCookie('cc', document.getElementById("saveInput").checked,365);
        checkLogin($('.username').val(),$('.password').val());
    }

	function addInfo(xhr){
        var returnVaule = $.parseJSON(xhr.responseText);
        console.log(returnVaule);
		if(returnVaule.code===0){
            if(returnVaule.hasOwnProperty("data")){
                if(returnVaule.data===""){
                    $('.loginTipsSpan').html('登陆失败!输入用户名或密码错误!!!');
                }
                else{
                    setCookie('loginState', '1', 365);
                    setCookie('uname', returnVaule.data.name, 365);
                    console.log('登陆成功!');
                    window.location.href = "main.html";
                }
            }
            else{
                $('.loginTipsSpan').html('登陆失败!输入用户名或密码错误!!!');
            }
        }
		else{
            $('.loginTipsSpan').html('登陆失败!输入用户名或密码错误!!!');
        }
	}

    $(function(){
        //若验证正确,则为true,最后判断是否能提交
        var isPwd = false
        var isUser = false;
        
        $(document).ready(function(){
            var user = getCookie("un");
            var pwd = getCookie("pw");
            var cc = getCookie("cc");
            // 判断是否存在cookie
            if (user) {
              $('.username').val(user);
              isPwd = true;
              $('.password').val(pwd);
              isUser = true;
            }
            if (cc=='false') {
              document.getElementById("saveInput").checked = "";
            }
            else {
              document.getElementById("saveInput").checked = "checked";
            }
        })
        $('.username').blur(function(){
            //正则表达式,验证用户名
            //用户名要1开头,第二位是3或4或5或6,最后一位以8或9结束,一共要11位
            //reg=/^1[3|4|5|6][0-9]\d{8,9}$/i;
            if($(this).val() == '' || $(this).val()  == '请输入您的账号'){
                $('.username').addClass('error-border');
                $('.loginTipsSpan').html('账户不能为空!!!');
                $(this).removeClass('success-border');
                isPwd = false;
            }
            //else if($('.username').val().length < 11){
            //    $('.loginTipsSpan').html('长度错误!!!');
            //    $('.username').addClass('error-border');
            //}
            //else if(!reg.test($('.username').val())){
            //    $('.loginTipsSpan').html('账户不存在!!!');
            //    $('.username').addClass('error-border');
            //}
            else{
                $('.username').removeClass('error-border');
                $('.username').addClass('success-border');
                $('.loginTipsSpan').html('');
                isUser = true;
            }
        });

        $('.password').blur(function(){
            //密码要a-z(大小写),1-9,总共6-22位
            //正则可以先了解
            //reg=/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,22}$/;
            if($(this).val() == ''){
                $(this).addClass('error-border');
                $('.loginTipsSpan').html('密码不能为空!!!');
                $(this).removeClass('success-border');
                isPwd = false;
            }
            //else if(!reg.test($(this).val())){
            //    $(this).addClass('error-border');
            //    $('.loginTipsSpan').html('密码格式不对!!!');
            //}
            else
            {
                $(this).addClass('success-border');
                $(this).removeClass('error-border');
                $('.loginTipsSpan').html('');
                isPwd = true;
            }
        });

        //$('form').submit(function(){
        $('#submit').click(function(){
            $('.loginTipsSpan').html('');
            //用户名密码验证通过则提交,验证不通过不提交
            if(isPwd && isUser){
                submitForm();
                //alert('提交成功!')
                //return true;
            }else{
                if(!($('.username').val() == '' || $('.username').val()  == '请输入您的账号')&&($('.password').val() != '')){
                    submitForm();
                }
                else{
                    $('.loginTipsSpan').html('用户名或密码不能为空!!!');
                    setCookie('cc', document.getElementById("saveInput").checked,365);
                    //return false;
                }
            }
        })
    })
</script>
</body>
</html>

有问题代码:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <link rel="icon" sizes="any" mask href="favicon.ico">
    <title>登陆页面</title>
    <style>
    *{
        margin:0;
        padding:0;
    }
    body{
        margin:0 auto;
        background-color:#E7FBFA;
    }
    #loginDiv{
        margin:0 auto;
        background-color:#E7FBFA;
        background-size:1024px 567px;
        min-width:824px;
        min-height:600px;
    }
    form{
        margin:0 auto;
        /* display:block; */
        /* border:1px solid #303a40; */
        /* padding: 200px 0 0 390px; */
        min-width:434px;
        min-height:400px;
    }
    ul{
        margin:40px auto 10px auto;
    }
    li{
        list-style:none;
        height:30px;
        text-align: center;
        margin-bottom:10px;
    }
    li span{
        display: block;
        color:#ff6633;
        font-size: 12px;
    }
    .error-border{
        border:1px solid #ff6633;
    }
    .success-border{
        border:1px solid #BBB;/*2eff37*/
    }
    .username, .password{
        padding:0 0 0 10px;
        color:#666;
        width:200px;
        height: 30px;
        /* border:1px solid #BBB; */
    }
    .username:focus, .password:focus {
        outline: none;
        border-color: #4488F9;
    }
    ::-webkit-input-placeholder { /* WebKit, Blink, Edge */    color: #BBB; font-size:14px}
    :-moz-placeholder { /* Mozilla Firefox 4 to 18 */   color: #BBB;  font-size:14px}
    ::-moz-placeholder { /* Mozilla Firefox 19+ */   color: #BBB;  font-size:14px}
    :-ms-input-placeholder { /* Internet Explorer 10-11 */   color: #BBB;  font-size:14px}
    .saveAccounts{
        margin:0 auto;
        padding:0;
        width:200px;
        height: 16px;
        font-size: 12px;
        color:#BBB;
    }
    .saveAccounts  input[type=checkbox] {
        cursor: pointer;
        position: relative;
        border:1px solid #BBB;
        background-color:rgba(0,0,0,0);
        color:#BBB;
        height: 16px;
        padding:0;
        margin:0;
        vertical-align:top;
    }
    .saveAccounts  input[type=checkbox]::after {
        position: absolute;
        top: 0;
        background-color: #fff;
        color: #fff;
        width: 14px;
        height: 14px;
        display: inline-block;
        visibility: visible;
        padding-left: 0px;
        text-align: center;
        content: ' ';
        border-radius: 2px;
        box-sizing: border-box;
        border: 1px solid #ddd;
    }
    .saveAccounts  input[type=checkbox]:checked::after {
        content: "";
        background-color: #037DF3;
        border-color: #037DF3;
        background-color: #037DF3;
    }
    .saveAccounts  input[type=checkbox]:checked::before {
        content: '';
        position: absolute;
        top: 1px;
        left: 5px;
        width: 3px;
        height: 8px;
        border: solid white;
        border-width: 0 2px 2px 0;
        transform: rotate(45deg);
        z-index: 1;
    }
    .loginTips{
        margin:0 auto;
        width:200px;
        height: 25px;
        color:#ff0000;
    }
    .submit{
        margin:0 auto;
        width:200px;
        height: 25px;
        text-align: center;
        background-color: #0066FF;
        padding:17px 0 0 0;
    }
    .submit input{
        color:#fff;
        font-size:14px;
        border-style:none;
        margin:0 auto;
        width: 200px;
        height: 25px;
        text-align: center;
        background-color:rgba(0,0,0,0);
    }
    </style>
</head>

<body>
<div id="loginDiv">
<form action="">
    <ul class='logging'>
        <li>
            <input class="username success-border" type="text" placeholder="请输入帐号" onfocus="focusFun(this)" onblur="blurFun(this)" maxlength="11">
        </li>
        <li>
            <input class="password success-border" type="password" placeholder="请输入密码">
        </li>
    </ul>
    <div class="saveAccounts">
        <input type="checkbox" id="saveInput" title="记住密码" checked="checked" onClick="saveCook()"/>&nbsp;记住密码
    </div>
    <div class="loginTips">
        <span class="loginTipsSpan"></span>
    </div>
    <div class="submit">
        <input id="submit" type="submit" value="登&nbsp;&nbsp;&nbsp;录">
    </div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    var request_url = 'http://127.0.0.1:8009/test';
    function getCookie(cname)
    {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) 
        {
            var c = ca[i].trim();
            if (c.indexOf(name)==0) return c.substring(name.length,c.length);
        }
        return "";
    }

    function setCookie(cname,cvalue,exdays){
        var d = new Date();
        d.setTime(d.getTime()+(exdays*24*60*60*1000));
        var expires = "expires="+d.toGMTString();
        document.cookie = cname+"="+cvalue+"; "+expires;
    }


    //请求数据
    function httpRequestData(url,inSendData,callBack)
    {
        //创建一个 XMLHTTPRequest 类型对象
        var xhr = null;
        if (window.XMLHttpRequest) {//标准浏览器
        xhr = new window.XMLHttpRequest;
        } else {//IE浏览器 
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.onreadystatechange = success;
        //open()方法开启请求
        xhr.open("POST", url, true); //请求的类型GET POST; true异步(默认) false同步
        //post请求要自己设置请求头
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//发送表单数据
        //xhr.setRequestHeader("Content-type", "application/json"); //发送json格式数据
        //xhr.setRequestHeader("Content-type","application/json;charset=utf-8"); //发送json格式数据
        //xhr.setRequestHeader("Content-type", "text/plain;charset=utf-8");发送纯文本
        //xhr.setRequestHeader("Content-type", "text/html;charset=utf-8");发送html文本
        //xhr.send(JSON.stringify(inSendData).replace(/\s+/g,""));
        //xhr.send(JSON.stringify(inSendData));
        xhr.send(inSendData);
        //xhr.send(null);

        function success() {
            if (xhr.readyState == 4) { //回传成功
                if(xhr.status == 200){
                    //console.info(xhr.responseText);
                    console.log('network success.');
                    callBack(xhr);
                    //return true;
                }
                else{
                    console.log("Problem retrieving XML data");
                    //return true;
                }
            }
            //else {
            //	console.log('network error.');
            //	return false;
            //}
        }
    }

    function focusFun(point){
        //触发焦点,若输入的值跟默认值一样,输入的值为空
        if(point.defaultValue == point.value){
            point.value = '';

        }
    }

    function blurFun(point){
        //失去焦点时,若值为空,则值等于默认值,也就是placeholder
        if(point.value == ''){
            point.value = point.defaultValue;
        }
    }

    function saveCook(){
        //取消记住密码,则删除
        if(!document.getElementById("saveInput").checked){
          // 删除cookie
          setCookie('un', '', 0);
          setCookie('pw', '', 0);
        }
        setCookie('cc', document.getElementById("saveInput").checked, 365);
    }

	function checkLogin(un,pwd) {
	  //var sendData = "{'login':'"+un+"','pass':'"+pwd+"'}";
	  var sendData = "login="+un+"&pass="+pwd;
	  httpRequestData(request_url + '/login/getUserInfo',sendData,addInfo);
	};

    function submitForm(){
        if(document.getElementById("saveInput").checked){
            setCookie('un', $('.username').val(),365);
            setCookie('pw', $('.password').val(),365);
        }
        setCookie('cc', document.getElementById("saveInput").checked,365);
        checkLogin($('.username').val(),$('.password').val());
    }

	function addInfo(xhr){
        var returnVaule = $.parseJSON(xhr.responseText);
        console.log(returnVaule);
		if(returnVaule.code===0){
            if(returnVaule.hasOwnProperty("data")){
                if(returnVaule.data===""){
                    $('.loginTipsSpan').html('登陆失败!输入用户名或密码错误!!!');
                }
                else{
                    setCookie('loginState', '1', 365);
                    setCookie('uname', returnVaule.data.name, 365);
                    console.log('登陆成功!');
                    window.location.href = "main.html";
                }
            }
            else{
                $('.loginTipsSpan').html('登陆失败!输入用户名或密码错误!!!');
            }
        }
		else{
            $('.loginTipsSpan').html('登陆失败!输入用户名或密码错误!!!');
        }
	}

    $(function(){
        //若验证正确,则为true,最后判断是否能提交
        var isPwd = false
        var isUser = false;
        
        $(document).ready(function(){
            var user = getCookie("un");
            var pwd = getCookie("pw");
            var cc = getCookie("cc");
            // 判断是否存在cookie
            if (user) {
              $('.username').val(user);
              isPwd = true;
              $('.password').val(pwd);
              isUser = true;
            }
            if (cc=='false') {
              document.getElementById("saveInput").checked = "";
            }
            else {
              document.getElementById("saveInput").checked = "checked";
            }
        })
        $('.username').blur(function(){
            //正则表达式,验证用户名
            //用户名要1开头,第二位是3或4或5或6,最后一位以8或9结束,一共要11位
            //reg=/^1[3|4|5|6][0-9]\d{8,9}$/i;
            if($(this).val() == '' || $(this).val()  == '请输入您的账号'){
                $('.username').addClass('error-border');
                $('.loginTipsSpan').html('账户不能为空!!!');
                $(this).removeClass('success-border');
                isPwd = false;
            }
            //else if($('.username').val().length < 11){
            //    $('.loginTipsSpan').html('长度错误!!!');
            //    $('.username').addClass('error-border');
            //}
            //else if(!reg.test($('.username').val())){
            //    $('.loginTipsSpan').html('账户不存在!!!');
            //    $('.username').addClass('error-border');
            //}
            else{
                $('.username').removeClass('error-border');
                $('.username').addClass('success-border');
                $('.loginTipsSpan').html('');
                isUser = true;
            }
        });

        $('.password').blur(function(){
            //密码要a-z(大小写),1-9,总共6-22位
            //正则可以先了解
            //reg=/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,22}$/;
            if($(this).val() == ''){
                $(this).addClass('error-border');
                $('.loginTipsSpan').html('密码不能为空!!!');
                $(this).removeClass('success-border');
                isPwd = false;
            }
            //else if(!reg.test($(this).val())){
            //    $(this).addClass('error-border');
            //    $('.loginTipsSpan').html('密码格式不对!!!');
            //}
            else
            {
                $(this).addClass('success-border');
                $(this).removeClass('error-border');
                $('.loginTipsSpan').html('');
                isPwd = true;
            }
        });

        $('form').submit(function(){
            $('.loginTipsSpan').html('');
            //用户名密码验证通过则提交,验证不通过不提交
            if(isPwd && isUser){
                submitForm();
                //alert('提交成功!')
                //return true;
            }else{
                if(!($('.username').val() == '' || $('.username').val()  == '请输入您的账号')&&($('.password').val() != '')){
                    submitForm();
                }
                else{
                    $('.loginTipsSpan').html('用户名或密码不能为空!!!');
                    setCookie('cc', document.getElementById("saveInput").checked,365);
                    //return false;
                }
            }
        })
    })
</script>
</body>
</html>



版权声明:本文为cwr888原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。