jsbin展示
登陸界面
輸入用戶名,密碼后點登陸
用戶名為xiaoming扇调,密碼為abcd1234時矿咕,顯示:“登陸成功”,
否則顯示:“用戶名密碼錯誤”
-
輸入正確的用戶名和密碼
-
輸入錯誤的用戶名和密碼
前端的 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 數(shù)據(jù)
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("用戶名密碼錯誤")
}
})