标签:username form 账号 value xhr 登陆 注册 var password
<!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>
标签:username,form,账号,value,xhr,登陆,注册,var,password 来源: https://blog.csdn.net/HAI6545/article/details/122434333
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。