原生JS 完成AJAX实现登录跳转页面功能

注:Html、CSS部分比较简单,js不懂的可以看注释哦。
Html:

 <div class="login">
    <div class="card">
      <form action="#">
       <input type="text" class="username" style="height:30px;font-size: 15px;line-height:30px;" placeholder="请输入用户名" autocomplete="on"> <br>
        <br>
        <input type="password" class="password"style="height:30px;font-size: 15px;line-height:30px;"placeholder="请输入密码"><br>
        <br>
        <input type="button" id="btn" style="background-color: #b3d4fc;width: 60%;height: 30px" value="登录">
      </form>
    </div>
  </div>

javascript:

window.onload=function () {
        var btn=document.getElementById("btn");
        btn.onclick=function () {
            var username=document.getElementsByClassName("username").value;//获取用户名input的value
            var password=document.getElementsByClassName("password").value;
            var data= {
                username,password  //将用户信息封装到data中方便发送给客户端
            }
            var stringData=JSON.stringify(data);//可无将data转换为字符串
            var ajax=null;
               if(window.XMLHttpRequest) {//创建ajax对象
                   ajax=new XMLHttpRequest();
               }else {
                   ajax=new ActiveXObject("Microsoft.XMLHTTP");
               }
               ajax.open("POST","http://39.96.87.225/mock/api/login",true);//通过POST异步请求方式,
            ajax.onreadystatechange=function () {//ajax状态吗发送改变触发onreadystatechange
                console.log(ajax.readyState);
                console.log(ajax.status);
                if(ajax.readyState==4){//判断ajax的状态码
                    if(ajax.status==200){//判断是否找到页面
                        var demo=ajax.responseText;//获得服务器传递的数据
                        location.href="main.html?_ijt=1r61fl4f86n1fouf4r2bv8etno";//请求成功跳转到主页面
                    }
                };
            }
            ajax.send(data);

        }

   }

css:

.login{
  margin: 0 auto;
  position: relative;
  top: 100px;
  height: 500px;
  width: 400px;
  border-color: aqua;
}
.card{
  width: 75%;
  margin: auto;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容