热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

HTML5本地存储里储存对象

HTML5本地存储里储存对象W3schools在HTML5里,网页可以把数据存储到用户得本地浏览器里。以前,这些数据保存在cookies里。但是Web存储更安全和快速。这
HTML5本地存储里储存对象

W3schools

在HTML5里,网页可以把数据存储到用户得本地浏览器里。
以前,这些数据保存在COOKIEs里。但是Web存储更安全和快速。
这些数据不必包含在每次服务器请求中,仅需要时使用。
它可以用来存储比较大得数据,而不会影响网站得性能。
数据存储依靠name/value得形式,一个网页只能访问它自己存储得数据。
不像COOKIEs那样,这种存储得容量很大(最小5MB)并且信息永远不会传递到服务器。



那么,你能在本地存储里存些什么呢?一个马戏团(一语双关)
你能存储字符串,数字,对象,复杂对象数组等。让我们看看从你得浏览器存储和获得数据得语法。


PS:不要存储敏感数据,比如密码,SSN,账户号等。



首先,让我们检查是否支持本地存储。



你能从这里查看本地存储得支持情况(caniuse.com/#search=localstorage)。
代码

if(typeof(Storage)!=="undefined")
  {
  // Code for localStorage/sessionStorage.
  }
else
  {
  // Sorry! No Web Storage support..
  }


获取和设置方法


字符串

var hello = "Hello World!!";
localStorage.setItem("hello",hello);
// get string
console.log(localStorage.getItem("hello")); // will return 'Hello World!!'


数字

var age = 99;
localStorage.setItem("myAge",age);
// get string
console.log(localStorage.getItem("age")); // will return 99 as string
// parsing to int
var age = parseInt(localStorage.getItem("age")); // 99
//or
var age = parseFloat(localStorage.getItem("age")); // 99

对象
var me = {name:'myname',age:99,gender:'myGender'};
localStorage.setItem("user",me);
//fetch object
console.log(localStorage.getItem("user")); // will return "[object Object]"


上面的方法存储对象并不能真得返回对象,这是因为当你求me对象值时,它返回一个字符串“[object Object]”。最终会保存到本地存储。下面时解决方案


var me = {name:'myname',age:99,gender:'myGender'};
localStorage.setItem("user",JSON.stringify(me));
//fetch object
console.log(localStorage.getItem("user")); // will return {"name":"myname","age":99,"gender":"myGender"}



很棒吧?但是JSON并不是支持所有浏览器,你可以通过这里检查(caniuse.com/#search=JSON)。
如果你已经使用JQuery,你也可以使用JQuery德parseJSON方法。
或者你也可以使用和JQuery一样得逻辑来解析JSON。引用自jquery-1.11.0.js(code.jquery.com/jquery-1.11.0.js)



jQuery.parseJSON = function( data ) {
    // Attempt to parse using the native JSON parser first
    if ( window.JSON && window.JSON.parse ) {
        // Support: Android 2.3
        // Workaround failure to string-cast null input
        return window.JSON.parse( data + "" );
    }
 
    var requireNonComma,
        depth = null,
        str = jQuery.trim( data + "" );
 
    // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
    // after removing valid tokens
    return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
 
        // Force termination if we see a misplaced comma
        if ( requireNonComma && comma ) {
            depth = 0;
        }
 
        // Perform no more replacements after returning to outermost depth
        if ( depth === 0 ) {
            return token;
        }
 
        // Commas must not follow "[", "{", or ","
        requireNOnComma= open || comma;
 
        // Determine new depth
        // array/object open ("[" or "{"): depth += true - false (increment)
        // array/object close ("]" or "}"): depth += false - true (decrement)
        // other cases ("," or primitive): depth += true - true (numeric cast)
        depth += !close - !open;
 
        // Remove this token
        return "";
    }) ) ?
        ( Function( "return " + str ) )() :
        jQuery.error( "Invalid JSON: " + data );
};




下面的代码来自SO(stackoverflow.com/)给出得解决方案还有JSON parse()和Stringify()得代码。你可以复制张贴下面得代码到你得js文件。检查windows.JSON是否存在,如果不,会加载它。


if(!(window.JSON && window.JSON.parse))
{
    (function() {
  function g(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null";
  else if("function"==b&&"undefined"==typeof a.call)return"object";return b};function h(a){a=""+a;if(/^\s*$/.test(a)?0:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/"[^"\\\n\r\u2028\u2029\x00-\x08\x10-\x1f\x80-\x9f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,"")))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);}function i(a,b){var c=[];j(new k(b),a,c);return c.join("")}function k(a){this.a=a}
  function j(a,b,c){switch(typeof b){case "string":l(b,c);break;case "number":c.push(isFinite(b)&&!isNaN(b)?b:"null");break;case "boolean":c.push(b);break;case "undefined":c.push("null");break;case "object":if(null==b){c.push("null");break}if("array"==g(b)){var f=b.length;c.push("[");for(var d="",e=0;eb?d+="000":256>b?d+="00":4096>b&&(d+="0");return m[a]=d+b.toString(16)}),'"')};window.JSON||(window.JSON={});"function"!==typeof window.JSON.stringify&&(window.JSON.stringify=i);"function"!==typeof window.JSON.parse&&(window.JSON.parse=h);
})();
}


然后你可以使用JSON.parse(object);   JSON.stringfy(string);


现在我们怎么存储复合对象?



var address = {flat : 'a1' , building : 'some Inn'}
var me = {name:'myname',age:99,gender:'myGender',address : address};
 
localStorage.setItem("user",JSON.stringify(me));
//fetch object
console.log(localStorage.getItem("user")); // will return {"name":"myname","age":99,"gender":"myGender","address":{"flat":"a1","building":"some Inn"}}
 
var me  = JSON.parse(localStorage.getItem("user")); // a Javascript object


(最后一句不知道怎么翻译了,两个版本)
简单吧,不要尝试利用本地存储的优势取代COOKIEs。

简单吗?去尝试本地存储相对于COOKIEs得优势吧。


原文:http://thejackalofJavascript.com/storing-objects-html5-local-storage/


推荐阅读
author-avatar
小花诸葛_630
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有