欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Html5中l(wèi)ocalStorage存儲(chǔ)JSON數(shù)據(jù)并讀取JSON數(shù)據(jù)的實(shí)現(xiàn)方法

  發(fā)布時(shí)間:2017-02-13 16:32:01   作者:佚名   我要評(píng)論
localStorage是HTML5提供的再客戶(hù)端實(shí)現(xiàn)本地存儲(chǔ)的一種方法,但是localStorage方法只能存儲(chǔ)字符串?dāng)?shù)據(jù),有時(shí)候我們需要存儲(chǔ)對(duì)象到本地比如:JSON;那么,localStorage怎么才能實(shí)現(xiàn)JSON數(shù)據(jù)的存儲(chǔ)與讀取呢?下面通過(guò)本文給大家講解解決思路,一起看看吧

localStorage是HTML5提供的再客戶(hù)端實(shí)現(xiàn)本地存儲(chǔ)的一種方法,但是localStorage方法只能存儲(chǔ)字符串?dāng)?shù)據(jù),有時(shí)候我們需要存儲(chǔ)對(duì)象到本地比如:JSON;那么,localStorage怎么才能實(shí)現(xiàn)JSON數(shù)據(jù)的存儲(chǔ)與讀取呢?

思路:既然localStorage只能存儲(chǔ)字符串?dāng)?shù)據(jù),那么我們就可以先把JSON對(duì)象轉(zhuǎn)換成字符串,然后用localStorage方法存儲(chǔ)起來(lái);等到需要用到這些JSON數(shù)據(jù)時(shí),先把它們讀取出來(lái),然后再轉(zhuǎn)換成JSON對(duì)象加以利用。

具體代碼如下:

var jsonData = {'name': '張三', 'age': 29}; // 定義一個(gè)JSON對(duì)象
var str_jsonData = JSON.stringify(jsonData);
console.log(typeof(str_jsonData)); // string
localStorage.setItem('localData', str_jsonData); // 存儲(chǔ)字符串?dāng)?shù)據(jù)到本地
var getLocalData = localStorage.getItem('localData'); // 讀取字符串?dāng)?shù)據(jù)
console.log(typeof(getLocalData)); // string
var jsonObj = JSON.parse(getLocalData);
console.log(typeof(jsonObj)); // obj
console.log(jsonObj.age); // 29

擴(kuò)展:

stringify()用于從一個(gè)對(duì)象解析出字符串;

parse()用于從一個(gè)字符串中解析出json對(duì)象。

以上所述是小編給大家介紹的Html5中l(wèi)ocalStorage存儲(chǔ)JSON數(shù)據(jù)并讀取JSON數(shù)據(jù)的實(shí)現(xiàn)方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論