html 属性存储对象,HTML5本地存储里储存对象

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值