我試圖將登錄用戶的名稱保存在瀏覽器的本地存盤中。檢查下面的代碼。
編碼:
localStorage.setItem('currentUser',btoa(JSON.stringify(user.name)))
解碼:
this.userName = JSON.parse(atob(localStorage.getItem('currentUser')))
現在的問題是,如果其中有日文字符,則user.name編碼有效,但是,在解碼名稱時,我沒有得到正確的文本。有什么解決辦法嗎?
uj5u.com熱心網友回復:
正如 Thomas 在評論中最初建議的那樣,您根本不應該使用任何編碼。
btoa需要字串形式的位元組,每個位元組一個字符。JSON.stringify回傳一個完整的 Unicode 文本的普通字串,而不是位元組。JSON.stringify當您想要將任意 JSON 可表示資料序列化為字串時使用。你已經有一個字串。
localStorage.setItem('currentUser', user.name);
this.userName = localStorage.getItem('currentUser');
uj5u.com熱心網友回復:
編碼:
const encode = (string) => {
return encodeURIComponent(string);
}
解碼:
const decode = (string) => {
return decodeURIComponent(string);
}
希望對你有用!
uj5u.com熱心網友回復:
您的代碼中的以下更新可以解決您的問題。
編碼:
localStorage.setItem('currentUser',btoa(unescape(encodeURIComponent(JSON.stringify(user.name)))))
解碼:
this.userName = JSON.parse(decodeURIComponent(escape(atob(localStorage.getItem('currentUser')))))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/489425.html
標籤:javascript 本地存储
