Pergunta

I'm building an HTML5 / Javascript / jQuery application for personal use. The application needs to literally just store two numbers in order to be able to function. What is the absolute lightest way I can store two numbers between script executions and page reloads? Ideally, the solution would not require the application to run on a server.

Foi útil?

Solução

localStorage would be easiest:

localStorage.setItem('a', 1);   // or localStorage.a = 1
localStorage.setItem('b', 2);

and to retrieve:

var a = +localStorage.getItem('a');  // or just a = +localStorage.a

Note that localStorage can only store strings, hence the + operator in that last line to cast the stored value back into a number. If you want to store objects, use JSON.stringify and JSON.parse.

Whether to use the direct properties or setItem style access is mostly a matter of personal choice. That said, in theory the methods are more rigorous and recommended as they avoid any possibility of confusing the built-in properties of the localStorage object with the keys that you're trying to store. Also, the methods can be shimmed on older browsers but direct property access cannot.

Outras dicas

Local storage is a good idea depending on your browser, here's a very good write up: http://diveintohtml5.info/storage.html

Plan old cookies will work as well. To set a cookie:

document.cookie = "MyNumber=1; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/";

To traverse the cookies:

var cookies = document.cookie.split(";"), i;
for(i = 0; i < cookies.length; i++)
{
  console.log(cookies[i]);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top