JS如何缓存一个变量。

时间:2022-08-20 20:29:36

What I want to do is to be able to create a variable, give it a value, close and reopen the window, and be able to retrieve the value I set in the last session. What is the simplest way to do that? JQuery answers are welcome.

我要做的是能够创建一个变量,给它一个值,关闭并重新打开窗口,并且能够检索我在上一个会话中设置的值。最简单的方法是什么?JQuery的答案是受欢迎的。

4 个解决方案

#1


49  

Use localStorage for that. It's persistent over sessions.

使用localStorage。它的持久会话。

Writing :

写作:

localStorage['myKey'] = 'somestring'; // only strings

Reading :

阅读:

var myVar = localStorage['myKey'] || 'defaultValue';

If you need to store complex structures, you might serialize them in JSON. For example :

如果需要存储复杂结构,可以用JSON序列化它们。例如:

Reading :

阅读:

var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

Writing :

写作:

localStorage['myKey'] = JSON.stringify(myVar);

Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

注意,您可能使用多个键。它们将被同一域中的所有页面检索。

Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

除非您想与IE7兼容,否则您没有理由使用过时的小cookie。

#2


10  

You have three options:

你有三个选择:

  1. Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
  2. 饼干:https://developer.mozilla.org/en-US/docs/DOM/document.cookie
  3. DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
  4. DOMStorage (sessionStorage或localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
  5. If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)
  6. 如果您的用户已登录,您可以将数据保存在服务器的DB中,该数据库对用户(或组)进行键控

#3


6  

You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.

如果在你的要求中允许的话,你可以创建一个cookie。如果您选择采用cookie路径,那么解决方案可以如下所示。此外,cookie的好处是在用户关闭浏览器并重新打开之后,如果cookie没有被删除,那么这个值将被持久化。

Cookie *Create and Store a Cookie:*

创建并存储一个Cookie:*

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

The function which will return the specified cookie:

返回指定cookie的函数:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

Display a welcome message if the cookie is set

如果设置了cookie,则显示欢迎消息

function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.

上面的解决方案是通过cookie保存值。这是一种相当标准的方法,无需将值存储在服务器端。

Jquery

Jquery

Set a value to the session storage.

为会话存储设置一个值。

Javascript:

Javascript:

$.sessionStorage( 'foo', {data:'bar'} );

Retrieve the value:

检索的值:

$.sessionStorage( 'foo', {data:'bar'} );

$.sessionStorage( 'foo' );Results:
{data:'bar'}

Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:

本地存储现在让我们来看看本地存储。例如,假设您有一个要持久化的变量数组。你可以这样做:

var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);

//...
var storedNames=JSON.parse(localStorage['names']);

Server Side Example using ASP.NET

服务器端示例使用ASP.NET。

Adding to Sesion

增加对话

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

// When retrieving an object from session state, cast it to // the appropriate type.

//从会话状态检索对象时,将其转换为//适当的类型。

ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

I hope that answered your question.

我希望这能回答你的问题。

#4


3  

check out my js lib for caching: https://github.com/hoangnd25/cacheJS

检查我的js lib来获取缓存:https://github.com/hoangnd25/cacheJS

My blog post: New way to cache your data with Javascript

我的博客文章:用Javascript缓存数据的新方法。

Features:

  • Conveniently use array as key for saving cache
  • 方便地使用数组作为密钥来保存缓存
  • Support array and localStorage
  • 支持数组和localStorage
  • Clear cache by context (clear all blog posts with authorId="abc")
  • 根据上下文清除缓存(用authorId=“abc”清除所有博客文章)
  • No dependency
  • 不依赖

Basic usage:

Saving cache:

保存缓存:

cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});

Retrieving cache:

检索缓存:

cacheJS.get({blogId: 1,type: 'view'});

Flushing cache

刷新缓存

cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});

cacheJS.removeByContext({author:'hoangnd'});

Switching provider

切换供应商

cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};

#1


49  

Use localStorage for that. It's persistent over sessions.

使用localStorage。它的持久会话。

Writing :

写作:

localStorage['myKey'] = 'somestring'; // only strings

Reading :

阅读:

var myVar = localStorage['myKey'] || 'defaultValue';

If you need to store complex structures, you might serialize them in JSON. For example :

如果需要存储复杂结构,可以用JSON序列化它们。例如:

Reading :

阅读:

var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

Writing :

写作:

localStorage['myKey'] = JSON.stringify(myVar);

Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

注意,您可能使用多个键。它们将被同一域中的所有页面检索。

Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

除非您想与IE7兼容,否则您没有理由使用过时的小cookie。

#2


10  

You have three options:

你有三个选择:

  1. Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
  2. 饼干:https://developer.mozilla.org/en-US/docs/DOM/document.cookie
  3. DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
  4. DOMStorage (sessionStorage或localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
  5. If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)
  6. 如果您的用户已登录,您可以将数据保存在服务器的DB中,该数据库对用户(或组)进行键控

#3


6  

You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.

如果在你的要求中允许的话,你可以创建一个cookie。如果您选择采用cookie路径,那么解决方案可以如下所示。此外,cookie的好处是在用户关闭浏览器并重新打开之后,如果cookie没有被删除,那么这个值将被持久化。

Cookie *Create and Store a Cookie:*

创建并存储一个Cookie:*

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

The function which will return the specified cookie:

返回指定cookie的函数:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

Display a welcome message if the cookie is set

如果设置了cookie,则显示欢迎消息

function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.

上面的解决方案是通过cookie保存值。这是一种相当标准的方法,无需将值存储在服务器端。

Jquery

Jquery

Set a value to the session storage.

为会话存储设置一个值。

Javascript:

Javascript:

$.sessionStorage( 'foo', {data:'bar'} );

Retrieve the value:

检索的值:

$.sessionStorage( 'foo', {data:'bar'} );

$.sessionStorage( 'foo' );Results:
{data:'bar'}

Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:

本地存储现在让我们来看看本地存储。例如,假设您有一个要持久化的变量数组。你可以这样做:

var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);

//...
var storedNames=JSON.parse(localStorage['names']);

Server Side Example using ASP.NET

服务器端示例使用ASP.NET。

Adding to Sesion

增加对话

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

// When retrieving an object from session state, cast it to // the appropriate type.

//从会话状态检索对象时,将其转换为//适当的类型。

ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

I hope that answered your question.

我希望这能回答你的问题。

#4


3  

check out my js lib for caching: https://github.com/hoangnd25/cacheJS

检查我的js lib来获取缓存:https://github.com/hoangnd25/cacheJS

My blog post: New way to cache your data with Javascript

我的博客文章:用Javascript缓存数据的新方法。

Features:

  • Conveniently use array as key for saving cache
  • 方便地使用数组作为密钥来保存缓存
  • Support array and localStorage
  • 支持数组和localStorage
  • Clear cache by context (clear all blog posts with authorId="abc")
  • 根据上下文清除缓存(用authorId=“abc”清除所有博客文章)
  • No dependency
  • 不依赖

Basic usage:

Saving cache:

保存缓存:

cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});

Retrieving cache:

检索缓存:

cacheJS.get({blogId: 1,type: 'view'});

Flushing cache

刷新缓存

cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});

cacheJS.removeByContext({author:'hoangnd'});

Switching provider

切换供应商

cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};