| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- function initLogin() {
- var form = document.getElementById("loginForm");
- form.addEventListener("submit", loginHandler);
- }
- function showMsg(text, isError) {
- if (isError === undefined) { isError = true; }
- var msg = document.getElementById("msg");
- msg.innerText = text;
- msg.style.color = isError ? "red" : "green";
- }
- function loginHandler(e) {
- e.preventDefault();
- var usernameEl = document.getElementById("username");
- var passwordEl = document.getElementById("password");
- var username = (usernameEl && usernameEl.value) || "";
- var password = (passwordEl && passwordEl.value) || "";
- var btn = document.getElementById("loginBtn");
- btn.disabled = true;
- btn.innerText = "登录中...";
- fetch("/api/auth/login", {
- method: "POST",
- headers: {
- "Content-Type": "application/json"
- },
- credentials: "include",
- body: JSON.stringify({ username: username, password: password })
- })
- .then(function (res) { return res.json(); })
- .then(function (data) {
- if (data.success) {
- window.location.href = "/";
- return;
- }
- showMsg("用户名或密码错误");
- })
- .catch(function () {
- showMsg("登录请求失败,请检查网络");
- })
- .finally(function () {
- btn.disabled = false;
- btn.innerText = "登录";
- });
- }
- initLogin();
|