const btnLogin = document.querySelector('#btn_login'); const inputPassword = document.querySelector('#login #password'); const btnLoginPage = document.querySelector('.btn-login'); const btnUserProfile = document.querySelector('.btn-userProfile'); const btnLogout = document.querySelector('.btn-logout'); const btnLoginPage_d = document.querySelector('.login-top .btn-login'); const btnUserProfile_d = document.querySelector('.login-top .btn-userProfile'); const btnLogout_d= document.querySelector('.login-top .btn-logout'); inputPassword.addEventListener('keyup', loginByEnter); btnLogin.addEventListener('click', login); function loginByEnter(e) { if (e.keyCode === 13) { e.preventDefault(); console.log('login!'); login(); } }; function login(){ console.log('login!'); var url = "http://www.choozmo.com:8887/login"; var xhr = new XMLHttpRequest(); xhr.open("POST", url); xhr.setRequestHeader("accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { console.log(xhr.responseText); // test responseOBJ = JSON.parse(xhr.responseText); // document.cookie = 'jwt_token='+responseOBJ.jwt_token // access_token -> jwt_token document.cookie = 'jwt_token='+responseOBJ.access_token; console.log(responseOBJ); if (responseOBJ.access_token!=null) { Swal.fire({ title: " 登入成功", icon: 'success', confirmButtonColor: '#3085d6', }); window.setTimeout(() => { window.location.href = 'user_profile.html'; }, 2000); btnLoginPage.style.display = 'none'; } else{ Swal.fire({ title: "登入失敗", icon: 'error', text: responseOBJ.detail, confirmButtonColor: '#3085d6', }); } } }; var data = "grant_type=&username=" + $('#username').val() + "&password="+$('#password').val()+"&scope=&client_id=&client_secret="; result = xhr.send(data); console.log(result); } function loginControl() { btnLoginPage.style.display = 'block'; btnLogout.style.display = 'none'; btnUserProfile.style.display = 'none'; btnLoginPage_d.style.display = 'block'; btnLogout_d.style.display = 'none'; btnUserProfile_d.style.display = 'none'; } loginControl();