js 保存多数据到本地,然后读出
基本js:
[code lang=”js”]
var cookieTool = {
set:function(name,value,expires,path,domain){
if(typeof expires=="undefined"){
expires = 365;
}
expires=new Date(new Date().getTime()+1000*3600*24*expires);
document.cookie=name+"="+escape(value)+((expires)?"; expires="+expires.toGMTString():"")+((path)?"; path="+path:"; path=/")+((domain)?";domain="+domain:"");
},
get:function(name){
var arr=document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr!=null){
return unescape(arr[2]);
}
return null;
},
clear:function(name,path,domain){
if(this.get(name)){
document.cookie=name+"="+((path)?"; path="+path:"; path=/")+((domain)?"; domain="+domain:"")+";expires=Fri, 02-Jan-1970 00:00:00 GMT";
}
}
};
function json_encode(mixed_val) {
// Returns the JSON representation of a value
//
// version: 906.1806
// discuss at: http://phpjs.org/functions/json_encode
// + original by: Public Domain (http://www.json.org/json2.js)
// + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: T.J. Leahy
// * example 1: json_encode([‘e’, {pluribus: ‘unum’}]);
// * returns 1: ‘[\n "e",\n {\n "pluribus": "unum"\n}\n]’
/*
http://www.JSON.org/json2.js
2008-11-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
*/
var json = this.window.JSON;
if (typeof json === ‘object’ && typeof json.stringify === ‘function’) {
return json.stringify(mixed_val);
}
var value = mixed_val;
var quote = function (string) {
var escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
var meta = { // table of character substitutions
‘\b’: ‘\\b’,
‘\t’: ‘\\t’,
‘\n’: ‘\\n’,
‘\f’: ‘\\f’,
‘\r’: ‘\\r’,
‘"’ : ‘\\"’,
‘\\’: ‘\\\\’
};
escapable.lastIndex = 0;
return escapable.test(string) ?
‘"’ + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === ‘string’ ? c :
‘\\u’ + (‘0000’ + a.charCodeAt(0).toString(16)).slice(-4);
}) + ‘"’ :
‘"’ + string + ‘"’;
};
var str = function(key, holder) {
var gap = ”;
var indent = ‘ ‘;
var i = 0; // The loop counter.
var k = ”; // The member key.
var v = ”; // The member value.
var length = 0;
var mind = gap;
var partial = [];
var value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === ‘object’ &&
typeof value.toJSON === ‘function’) {
value = value.toJSON(key);
}
// What happens next depends on the value’s type.
switch (typeof value) {
case ‘string’:
return quote(value);
case ‘number’:
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : ‘null’;
case ‘boolean’:
case ‘null’:
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce ‘null’. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
case ‘object’:
// If the type is ‘object’, we might be dealing with an object or an array or
// null.
// Due to a specification blunder in ECMAScript, typeof null is ‘object’,
// so watch out for that case.
if (!value) {
return ‘null’;
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === ‘[object Array]’) {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || ‘null’;
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? ‘[]’ :
gap ? ‘[\n’ + gap +
partial.join(‘,\n’ + gap) + ‘\n’ +
mind + ‘]’ :
‘[‘ + partial.join(‘,’) + ‘]’;
gap = mind;
return v;
}
// Iterate through all of the keys in the object.
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ‘: ‘ : ‘:’) + v);
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? ‘{}’ :
gap ? ‘{\n’ + gap + partial.join(‘,\n’ + gap) + ‘\n’ +
mind + ‘}’ : ‘{‘ + partial.join(‘,’) + ‘}’;
gap = mind;
return v;
}
};
// Make a fake root object containing our value under the key of ”.
// Return the result of stringifying the value.
return str(”, {
”: value
});
}
function json_decode(str_json) {
// Decodes the JSON representation into a PHP value
//
// version: 906.1806
// discuss at: http://phpjs.org/functions/json_decode
// + original by: Public Domain (http://www.json.org/json2.js)
// + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: T.J. Leahy
// * example 1: json_decode(‘[\n "e",\n {\n "pluribus": "unum"\n}\n]’);
// * returns 1: [‘e’, {pluribus: ‘unum’}]
/*
http://www.JSON.org/json2.js
2008-11-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
*/
var json = this.window.JSON;
if (typeof json === ‘object’ && typeof json.parse === ‘function’) {
return json.parse(str_json);
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
var j;
var text = str_json;
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return ‘\\u’ +
(‘0000’ + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with ‘()’ and ‘new’
// because they can cause invocation, and ‘=’ because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE’s and Safari’s regexp engines. First we
// replace the JSON backslash pairs with ‘@’ (a non-JSON character). Second, we
// replace all simple value tokens with ‘]’ characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ‘]’ or
// ‘,’ or ‘:’ or ‘{‘ or ‘}’. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, ‘@’).
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ‘]’).
replace(/(?:^|:|,)(?:\s*\[)+/g, ”))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The ‘{‘ operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval(‘(‘ + text + ‘)’);
return j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError(‘json_decode’);
}
[/code]
使用方法:
[code lang=”js”]
$(".main-box ul li").click(function(){//写入缓存
var $url = $(this).find("a").has("img").attr("href");
var $imgurl = $(this).find("a").has("img").find("img").attr("src");
var $title = $(this).find("a").has("img").attr("title");
var $yjia = $(this).find(".market-price").text();
var $xjia = $(this).find(".cur-price").text();
var $str = new Array($title,$url,$imgurl,$yjia,$xjia);
var $sdiv = new Array();
$sdivc=json_decode(cookieTool.get("divurl"));//获取数据并反json
//alert($sdivc);
if($sdivc!=undefined){ $sdiv = $sdivc};
//$sdiv.push($str);
$sdiv.unshift($str);//添加到数据开头
//console.log($sdiv);
//console.log($sdivc);
cookieTool.set("divurl",json_encode($sdiv));//储存数据 用json
});
[/code]
调用缓存:
[code lang=”js”]
var $str1="";
var $sdivour=json_decode(cookieTool.get("divurl"));//获取数据并反json
//console.log($sdivour);
for(var $i=0;$i<$sdivour.length;$i++){
//alert($sdivour[$i]);
$str1+='<li>title:’+$sdivour[$i][0]+’,url:’+$sdivour[$i][1]+'</li>’;//str1写入到你需要的dom
}
[/code]