<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="">
<h3>用户登陆</h3>
用户名: <input type="text" id="username"> <span id="info"></span><br>
密码:<input type="password" id="password"> <br>
<input type="button" id="loginBtn" value=" 登陆 ">
</form>
<script>
document.getElementById("loginBtn").onclick = function() {
// 1. 获取用户名和密码
var un = document.getElementById("username").value;
var pwd = document.getElementById("password").value;
// 2. 将用户名和密码以某种形式传递给后台 (ajax)
var xhr = new XMLHttpRequest();
var url = "http://localhost:3000";
xhr.open("post", url, true);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200){
var o = JSON.parse(xhr.responseText);
if(o.code === 400){
document.getElementById("info").innerHTML = "用户名或密码错误";
}else{
window.location.href = "01-ajax访问头条新闻.html";
}
}
};
/*
"{"username":"...", "password":".."}"
*/
var user = {
username: un,
password: pwd
};
xhr.send(JSON.stringify(user));
// 3. 接收后台响应的数据
};
</script>
</body>
</html>