0
点赞
收藏
分享

微信扫一扫

使用注册账号登陆

丹柯yx 2022-01-11 阅读 90
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style>
    td:first-child{
        text-align: right;
    }
</style>
<body>
<form action="">
    <table align="center">
        <caption><h2>登录</h2></caption>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit"></td>
        </tr>
    </table>
</form>
</body>
<script>
// 表单提交事件
// 阻止默认行为
// 验证用户名和密码不为空
// ajax发送数据给服务器
// 获取元素
var form = document.querySelector('form');
var username = document.querySelector('[name="username"]');
var password = document.querySelector('[name="password"]');
// 绑定事件
form.onsubmit = function(){
    // 验证表单
    if(username.value.trim() === '' || password.value.trim() === ''){
        alert('用户名和密码都不能为空')
        return false
    }
    // 发送请求
    var xhr = new XMLHttpRequest;
    xhr.open('post','http://localhost:8888/users/login');
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    xhr.send(`username=${username.value}&password=${password.value}`)
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
            if(xhr.status>=200 && xhr.status<300){
                var res = xhr.responseText;
                res = JSON.parse(res)
                var {message, code} = res

                // console.log(res);
                if(code === 1){
                    alert(message)
                  
                    // cookie所能识别的时间是世界标准时间,new Date得到的是中国标准标准时间 - 时间不精准 - 所有每次设置cookie有效期的时候,应该将中国标准时间回调8小时
                   /*
                    1.按照域名存储的,当前域名下设置的cookie,只能在当前域名下使用
                    2.cookie只能在http协议中使用
                    3.cookie存在浏览器,换个浏览器就不存在了,客户端的存储不安全 - 不存敏感数据
                    4.cookie在浏览器中有大小和数量的限制,大小大概4kb左右,数量大概在150条左右
                    5.时效性,默认是会话级别
                    */

                    var date = new Date()
                    date.setTime(date.getTime()+10*1000)
                    // console.log(date);
                    document.cookie = 'username='+username.value+';expires='+date
                    document.cookie = 'age=12;expires='+date
                    document.cookie = 'sex=女;expires='+date
                    document.cookie = 'height=180;expires='+date
                    // 设置多个cookie,就赋值多次


                    // 跳转到首页
                    // location.href = './04-首页.html'
                }else{
                    alert(message)
                }
            }
        }
    }
    // 阻止默认行为
    return false
}
</script>
</html>
举报

相关推荐

0 条评论