JQuery實現(xiàn)表單監(jiān)聽,登錄數(shù)據(jù)提交,返回token儲存,跳轉登錄成功頁面
分為四步:第一步 阻止默認提交行為;第二步 獲取表單數(shù)據(jù);第三步 發(fā)起ajax請求;第四步 存儲token并跳轉頁面
示例代碼中的layer使用的layui中的方法,快速獲取表單數(shù)據(jù)是jQuery中的serialize方法,存儲返回的token使用了瀏覽器對象的localStorage,跳轉使用了瀏覽器的location對象。

.ajax({
method: 'POST',
url: '/api/login',
// 快速獲取表單中的數(shù)據(jù)
data: $(this).serialize(),
success: function (res) {
if (res.status !== 0) {
return layer.msg('登錄失??!')
}
layer.msg('登錄成功!')
// 將登錄成功得到的 token 字符串,保存到 localStorage 中
localStorage.setItem('token', res.token)
// 跳轉到后臺主頁
location.href = '/index.html'
}
})
})
localstorage 在瀏覽器的 API 有兩個:localStorage 和sessionStorage,存在于 window 對象中:localStorage 對應 window.localStorage,sessionStorage 對應 window.sessionStorage。
local storage以鍵值對的形式存儲,數(shù)據(jù)類型是string,如果返回其他類型會自動轉為string,主要的方法有
