jsbin展示
登陆界面
Paste_Image.png
输入用户名,密码后点登陆
用户名为xiaoming,密码为abcd1234时,显示:“登陆成功”,
否则显示:“用户名密码错误”
-
输入正确的用户名和密码
Paste_Image.png -
输入错误的用户名和密码
Paste_Image.png
前端的 html 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="user" placeholder="用户名">
<input type="text" id="pwd" placeholder="密码">
<button id="btn">登陆</button>
</body>
<script>
var btn = $("#btn");
var user = $("#user");
var pwd = $("#pwd")
btn.addEventListener('click', function() {
ajax({
url: 'login', //接口地址
type: 'get', // 类型, post 或者 get,
data: {
username: user.value,
password: pwd.value
},
success: function(ret) {
console.log(ret); // {status: 0}
},
error: function() {
console.log('出错了');
}
})
});
function $(str) {
return document.querySelector(str);
}
function ajax(opts) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 304) {
var result = xhr.responseText;
opts.success(result);
} else {
opts.error();
}
}
}
var query = "?";
for (var key in opts.data) {
query += key + "=" + opts.data[key] + "&"
}
// query = query.slice(0, -1)
xhr.open(opts.type, opts.url + query, true)
xhr.send()
}
</script>
</html>
后端的 router.js 代码 mock 数据
app.get("/login", function(req, res) {
var user = req.query.username;
var pwd = req.query.password;
if (user === "xiaoming" && pwd === "abcd1234") {
res.send("登录成功")
} else {
res.send("用户名密码错误")
}
})