在靜態文件 js/user上當下,的 auth.js 文件中javascript
$(function () { let $username = $('#user_name'); // 選擇id爲user_name的網頁元素,須要定義一個id爲user_name let $img = $(".form-item .captcha-graph-img img"); // 獲取圖像標籤 let sImageCodeId = ""; // 定義圖像驗證碼ID值 let $mobile = $('#mobile'); // 選擇id爲mobile的網頁元素,須要定義一個id爲mobile let $smsCodeBtn = $('.form-item .sms-captcha');// 獲取短信驗證碼按鈕元素,須要定義一個id爲input_smscode let $imgCodeText = $('#input_captcha'); // 獲取用戶輸入的圖片驗證碼元素,須要定義一個id爲input_captcha let $register = $('.form-contain'); // 獲取註冊表單元素 // 一、圖片驗證碼邏輯 // 經過uuid生成驗證碼編號 // 拼接驗證碼地址 // 設置驗證碼圖片標籤的src generateImageCode(); // 生成圖像驗證碼圖片 $img.click(generateImageCode); // 點擊圖片驗證碼生成新的圖片驗證碼圖片 // 二、用戶名驗證邏輯 $username.blur(function () { fn_check_usrname(); }); // 三、手機號驗證邏輯 // 判斷用戶手機號是否註冊 $mobile.blur(function () { fn_check_mobile(); }); // 四、發送短信驗證碼邏輯 $smsCodeBtn.click(function () { // 判斷手機號是否輸入 if (fn_check_mobile() !== "success") { return } // 判斷用戶是否輸入圖片驗證碼 let text = $imgCodeText.val(); // 獲取用戶輸入的圖片驗證碼文本 if (!text) { message.showError('請填寫驗證碼!'); return } if (!sImageCodeId) { message.showError('圖片UUID爲空'); return } // 正常 let SdataParams = { "mobile": $mobile.val(), // 獲取用戶輸入的手機號 "text": text, // 獲取用戶輸入的圖片驗證碼文本 "image_code_id": sImageCodeId // 獲取圖片UUID }; // for test // let SdataParams = { // "mobile": "1806508", // 獲取用戶輸入的手機號 // "text": "ha3d", // 獲取用戶輸入的圖片驗證碼文本 // "image_code_id": "680a5a66-d9e5-4c3c-b8ea" // 獲取圖片UUID // }; // 向後端發送請求 $.ajax({ // 請求地址 url: "/sms_codes/", // 請求方式 type: "POST", // 向後端發送csrf token // headers: { // // 根據後端開啓的CSRFProtect保護,cookie字段名固定爲X-CSRFToken // "X-CSRFToken": getCookie("csrf_token") // }, // data: JSON.stringify(SdataParams), data: JSON.stringify(SdataParams), // 請求內容的數據類型(前端發給後端的格式) contentType: "application/json; charset=utf-8", // 響應數據的格式(後端返回給前端的格式) dataType: "json", async: false }) .done(function (res) { if (res.errno === "0") { // 倒計時60秒,60秒後容許用戶再次點擊發送短信驗證碼的按鈕 message.showSuccess('短信驗證碼發送成功'); let num = 60; // 設置一個計時器 let t = setInterval(function () { if (num === 1) { // 若是計時器到最後, 清除計時器對象 clearInterval(t); // 將點擊獲取驗證碼的按鈕展現的文本恢復成原始文本 $smsCodeBtn.html("獲取驗證碼"); } else { num -= 1; // 展現倒計時信息 $smsCodeBtn.html(num + "秒"); } }, 1000); } else { message.showError(res.errmsg); } }) .fail(function(){ message.showError('服務器超時,請重試!'); }); }); // 五、註冊邏輯 $register.submit(function (e) { // 阻止默認提交操做 e.preventDefault(); // 獲取用戶輸入的內容 let sUsername = $username.val(); // 獲取用戶輸入的用戶名字符串 let sPassword = $("input[name=password]").val(); let sPasswordRepeat = $("input[name=password_repeat]").val(); let sMobile = $mobile.val(); // 獲取用戶輸入的手機號碼字符串 let sSmsCode = $("input[name=sms_captcha]").val(); // 判斷用戶名是否已註冊 if (fn_check_usrname() !== "success") { return } // 判斷手機號是否爲空,是否已註冊 if (fn_check_mobile() !== "success") { return } // 判斷用戶輸入的密碼是否爲空 if ((!sPassword) || (!sPasswordRepeat)) { message.showError('密碼或確認密碼不能爲空'); return } // 判斷用戶輸入的密碼和確認密碼長度是否爲6-20位 if ((sPassword.length < 6 || sPassword.length > 20) || (sPasswordRepeat.length < 6 || sPasswordRepeat.length > 20)) { message.showError('密碼和確認密碼的長度需在6~20位之內'); return } // 判斷用戶輸入的密碼和確認密碼是否一致 if (sPassword !== sPasswordRepeat) { message.showError('密碼和確認密碼不一致'); return } // 判斷用戶輸入的短信驗證碼是否爲6位數字 if (!(/^\d{6}$/).test(sSmsCode)) { message.showError('短信驗證碼格式不正確,必須爲6位數字!'); return } // 發起註冊請求 // 一、建立請求參數 let SdataParams = { "username": sUsername, "password": sPassword, "password_repeat": sPasswordRepeat, "mobile": sMobile, "sms_code": sSmsCode }; // 二、建立ajax請求 $.ajax({ // 請求地址 url: "/users/register/", // url尾部須要添加/ //url: "/users/res/", // url尾部須要添加/ // 請求方式 type: "POST", data: JSON.stringify(SdataParams), // 請求內容的數據類型(前端發給後端的格式) contentType: "application/json; charset=utf-8", // 響應數據的格式(後端返回給前端的格式) dataType: "json", }) .done(function (res) { if (res.errno === "0") { // 註冊成功 message.showSuccess('恭喜你,註冊成功!'); setTimeout(function () { // 註冊成功以後重定向到主頁 //window.location.href = '/'; //重定向到原頁面 window.location.href = document.referrer; }, 1000) } else { // 註冊失敗,打印錯誤信息 message.showError(res.errmsg); } }) .fail(function(){ message.showError('服務器超時,請重試!'); }); }); // 生成一個圖片驗證碼的編號,並設置頁面中圖片驗證碼img標籤的src屬性 function generateImageCode() { // 一、生成一個圖片驗證碼隨機編號 sImageCodeId = generateUUID(); // 二、拼接請求url /image_codes/<uuid:image_code_id>/ let imageCodeUrl = "/image_codes/" + sImageCodeId + "/"; // 三、修改驗證碼圖片src地址 $img.attr('src', imageCodeUrl) } // 生成圖片UUID驗證碼 function generateUUID() { let d = new Date().getTime(); if (window.performance && typeof window.performance.now === "function") { d += performance.now(); //use high-precision timer if available } let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { let r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); return uuid; } // 判斷用戶名是否已經註冊 function fn_check_usrname() { let sUsername = $username.val(); // 獲取用戶名字符串 let sReturnValue = ""; if (sUsername === "") { message.showError('用戶名不能爲空!'); return } if (!(/^\w{5,20}$/).test(sUsername)) { message.showError('請輸入5-20個字符的用戶名'); return } // 發送ajax請求,去後端查詢用戶名是否存在 $.ajax({ url: '/usernames/' + sUsername + '/', type: 'GET', dataType: 'json', async: false }) .done(function (res) { if (res.data.count !== 0) { message.showError(res.data.username + '已註冊,請從新輸入!') sReturnValue = "" } else { message.showInfo(res.data.username + '能正常使用!') sReturnValue = "success" } }) .fail(function () { message.showError('服務器超時,請重試!'); sReturnValue = "" }); return sReturnValue } // 判斷手機號是否註冊 function fn_check_mobile() { let sMobile = $mobile.val(); // 獲取用戶輸入的手機號碼字符串 let sReturnValue = ""; if (sMobile === "") { message.showError('手機號不能爲空!'); return } if (!(/^1[345789]\d{9}$/).test(sMobile)) { message.showError('手機號碼格式不正確,請從新輸入!'); return } $.ajax({ url: '/mobiles/' + sMobile + '/', type: 'GET', dataType: 'json', async: false }) .done(function (res) { if (res.data.count !== 0) { message.showError(res.data.mobile + '已註冊,請從新輸入!') sReturnValue = "" } else { message.showSuccess(res.data.mobile + '能正常使用!'); sReturnValue = "success" } }) .fail(function () { message.showError('服務器超時,請重試!'); sReturnValue = "" }); return sReturnValue } // get cookie using jQuery function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { let cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } // Setting the token on the AJAX request $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); });
在靜態文件下 js/user 目錄下,的login.js文件中html
/** * Created by Administrator on 2018/12/15 0015. */ $(function () { let $login = $('.form-contain'); // 獲取登陸表單元素 // for test // console.log(document.referrer); // 將referrer url 打印到終端 // 登陸邏輯 $login.submit(function (e) { // 阻止默認提交操做 e.preventDefault(); // 獲取用戶輸入的帳號信息 let sUserAccount = $("input[name=telephone]").val(); // 獲取用戶輸入的用戶名或者手機號 // 判斷用戶輸入的帳號信息是否爲空 if (sUserAccount === "") { message.showError('用戶帳號不能爲空'); return } // 判斷輸入手機號格式或者用戶名格式是否正確 if (!(/^\w{5,20}$/).test(sUserAccount) || !(/^\w{5,20}$/).test(sUserAccount)) { message.showError('請輸入合法的用戶帳號:5-20個字符的用戶名或者11位手機號'); return } // 獲取用戶輸入的密碼 let sPassword = $("input[name=password]").val(); // 獲取用戶輸入的密碼 // 判斷用戶輸入的密碼是否爲空 if (!sPassword) { message.showError('密碼不能爲空'); return } // 判斷用戶輸入的密碼是否爲6-20位 if (sPassword.length < 6 || sPassword.length > 20) { message.showError('密碼的長度需在6~20位之內'); return } // 獲取用戶是否勾許"記住我",勾許爲true,不勾許爲false let bStatus = $("input[type='checkbox']").is(":checked"); // 獲取用戶是否選擇記住我,勾上表明true,沒勾上代碼false // 發起登陸請求 // 建立請求參數 let SdataParams = { "user_account": sUserAccount, "password": sPassword, "remember_me": bStatus }; // 建立ajax請求 $.ajax({ // 請求地址 url: "/users/login/", // url尾部須要添加/ // 請求方式 type: "POST", data: JSON.stringify(SdataParams), // 請求內容的數據類型(前端發給後端的格式) contentType: "application/json; charset=utf-8", // 響應數據的格式(後端返回給前端的格式) dataType: "json", }) .done(function (res) { if (res.errno === "0") { // 註冊成功 message.showSuccess('恭喜你,登陸成功!'); setTimeout(function () { // 註冊成功以後重定向到打開登陸頁面以前的頁面 window.location.href = document.referrer; }, 1000) } else { // 登陸失敗,打印錯誤信息 message.showError(res.errmsg); } }) .fail(function(){ message.showError('服務器超時,請重試!'); }); }); // get cookie using jQuery function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { let cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } // Setting the token on the AJAX request $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); });
在 html 文件中要引入對應 js 文件,級標籤的對名稱 ,前端