login.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const btnLogin = document.querySelector('#btn_login');
  2. const inputPassword = document.querySelector('#login #password');
  3. const btnLoginPage = document.querySelector('.btn-login');
  4. const btnUserProfile = document.querySelector('.btn-userProfile');
  5. const btnLogout = document.querySelector('.btn-logout');
  6. const btnLoginPage_d = document.querySelector('.login-top .btn-login');
  7. const btnUserProfile_d = document.querySelector('.login-top .btn-userProfile');
  8. const btnLogout_d= document.querySelector('.login-top .btn-logout');
  9. inputPassword.addEventListener('keyup', loginByEnter);
  10. btnLogin.addEventListener('click', login);
  11. function loginByEnter(e) {
  12. if (e.keyCode === 13) {
  13. e.preventDefault();
  14. console.log('login!');
  15. login();
  16. }
  17. };
  18. function login(){
  19. console.log('login!');
  20. var url = "https://www.choozmo.com:8887/login";
  21. var xhr = new XMLHttpRequest();
  22. xhr.open("POST", url);
  23. xhr.setRequestHeader("accept", "application/json");
  24. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  25. xhr.onreadystatechange = function () {
  26. if (xhr.readyState === 4) {
  27. console.log(xhr.responseText); // test
  28. responseOBJ = JSON.parse(xhr.responseText);
  29. // document.cookie = 'jwt_token='+responseOBJ.jwt_token // access_token -> jwt_token
  30. document.cookie = 'jwt_token='+responseOBJ.access_token;
  31. console.log(responseOBJ);
  32. if (responseOBJ.access_token!=null)
  33. {
  34. var title = "登入成功";
  35. alert(lang); // test
  36. if (lang == 'en') { // 英文版訊息
  37. title = "Login Successfully!"
  38. }
  39. Swal.fire({
  40. title: title,
  41. icon: 'success',
  42. confirmButtonColor: '#3085d6',
  43. });
  44. window.setTimeout(() => {
  45. window.location.href = 'user_profile2.html';
  46. }, 2000);
  47. btnLoginPage.style.display = 'none';
  48. }
  49. else{
  50. var title = "登入失敗";
  51. if (lang == 'en') { // 英文版訊息
  52. title = "Login Failed!"
  53. }
  54. Swal.fire({
  55. title: title,
  56. icon: 'error',
  57. text: responseOBJ.detail,
  58. confirmButtonColor: '#3085d6',
  59. });
  60. }
  61. }
  62. };
  63. var data = "grant_type=&username=" + $('#username').val() + "&password="+$('#password').val()+"&scope=&client_id=&client_secret=";
  64. result = xhr.send(data);
  65. console.log(result);
  66. }
  67. function loginControl() {
  68. btnLoginPage.style.display = 'block';
  69. btnLogout.style.display = 'none';
  70. btnUserProfile.style.display = 'none';
  71. btnLoginPage_d.style.display = 'block';
  72. btnLogout_d.style.display = 'none';
  73. btnUserProfile_d.style.display = 'none';
  74. }
  75. loginControl();