代码改变世界

html5之本地存储localStorage示例

2016-01-27 14:56  妙笔生花  阅读(466)  评论(0编辑  收藏  举报
<!-- 
注意: 
index.html 文件中的IP指的是服务器的访问地址,请根据具体需求走。本案例只做参考。
返回的json格式,大家可通过本地.json文件模拟,具体格式如下:
{
    "cindex": 0,
    "max": 0,
    "min": 0,
    "p_id": 0,
    "paper_id": 0,
    "score": "",
    "scoreRule": "",
    "score_type": "",
    "title": "哈哈哈哈哈",
    "totalNum": 0,
    "type": 1,
    "unmber": ""
}
-->        

 

index.html 文件

<!doctype html>
<html lang="en">
 <head>
  <title> html5本地缓存示例 </title>
  <meta charset="utf-8">
  <meta name="description" content="html5本地缓存示例">
 </head>

 <body>
 <div>
    <input type="text" id="jsonName"/>
    <input type="button" value="按存储名查询" onclick="findStorage()"/>
    <input type="button" value="按存储名删除" onclick="deleteStorage()"/>
    <div id="storageInfo">
    </div>
 </div>

 <p>
    1、针对客户端而言,localStorage 本地永久存储;sessionStorage 临时存储;<br/>
    2、localStorage 与 sessionStorage 存储大小5MB;注意不要存储敏感信息<br/>
    3、以ajax取得数据为例,将返回的json存储至localStorage中
 </p>
 <script type="text/javascript" src="js/lib/jquery-1.9.1.min.js"></script>
 <script>
    /*定义对象*/
    var questionIPort = "http://IP/yitaifront/normalcase/test?id=";

    function getElObj(elId){//取对象
        return document.getElementById(elId);
    }

    function isEmptyObj(data){//判空
        if(data == null || data == ""){
            return true;
        }else{
            return false;
        }
    }

    function saveStorage(saveName,data){//存数据
        if(isEmptyObj(data)){
            try{
                 console.log("数据保存失败");
                 window.localStorage.setItem(saveName,"");
            }catch(oException){
                 if(oException.name == 'QuotaExceededError'){
                    removeAllStorage(saveName, "");  
                 }
            }
        }else{
            var str = JSON.stringify(data);
            try{
                 window.localStorage.setItem(saveName,str);
                 console.log("整个数据已保存,取值name为"+saveName);
            }catch(oException){
                 if(oException.name == 'QuotaExceededError'){
                    removeAllStorage(saveName, str);  
                 }
            }
        }
    }

    function removeAllStorage(saveName, str){//清空所有
        console.log('超出本地存储限定范围!');
        //如果历史信息不重要了,可清空后再设置
        localStorage.clear();
        window.localStorage.setItem(saveName,str);
    }

    function removeStorageByCount(count){
        var countInt = count-0;
        console.log(window.localStorage);
        for(var i = 1; i <= countInt; i++){
            var storageKey = window.localStorage.key(i);
            console.log(""+i+"个对象的key值为"+storageKey);
            window.localStorage.removeItem(storageKey);
        }
        console.log("超出本地存储限定范围!共删除"+i+"个对象");
    }

    function findStorage(){//查数据
        var targetObj = getElObj("jsonName").value;
        if(isEmptyObj(targetObj)){
            getElObj("storageInfo").innerHTML = "";
            return ;
        }else{
            var str = window.localStorage.getItem(targetObj);
            var data = JSON.parse(str);
            if(data != null && data != ""){
                getElObj("storageInfo").innerHTML = data.title;
                console.log(data.title);    
            }else{
                getElObj("storageInfo").innerHTML = "";
            }
        }
        console.log("查找......");
    }

    function deleteStorage(){//删数据
        var targetObj = getElObj("jsonName").value;
        if(isEmptyObj(targetObj)){
            return ;
        }else{
            window.localStorage.removeItem(targetObj);
            getElObj("storageInfo").innerHTML = "删除成功";
        }
        console.log("删除......");
    }

    function findQuestInfo(questionIPort, saveId){//接口调用
        $.ajax({
            url: questionIPort+saveId,
            dataType: "json",
            type: "get",
            beforeSend: function() {//请求前

            },
            success: function(response) {//请求成功
                if(response.code == 200){
                    saveStorage("questStorage"+saveId,response.data);
                }else{
                    saveStorage("questStorage"+saveId,"");
                }
            },
            complete: function() {//请求完成

            },
            error: function() {//请求出错
                saveStorage("questStorage"+saveId,"");
            }
        });
    }

    //查询保存数据 
    findQuestInfo(questionIPort, "118"); //单选题
    findQuestInfo(questionIPort, "181"); //多选题
    findQuestInfo(questionIPort, "135"); //填空题
    findQuestInfo(questionIPort, "182"); //主观题
    findQuestInfo(questionIPort, "166"); //数字记忆
    findQuestInfo(questionIPort, "167"); //词语记忆
    /*setTimeout(function(){
        removeStorageByCount(2);
    },3000);*/
    
 </script>
 </body>
</html>