最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Save data in JS - Stack Overflow

programmeradmin1浏览0评论

I want to be able to save data to a database or an external file in JavaScript. For example; you can have a high score variable in pong. The program checks if your current score is higher than the high score variable and changes when your score is higher. This is cool, but once you reload the tab, everything is reset. Anything that works I will except. Even changing the source code of the program is fine

I want to be able to save data to a database or an external file in JavaScript. For example; you can have a high score variable in pong. The program checks if your current score is higher than the high score variable and changes when your score is higher. This is cool, but once you reload the tab, everything is reset. Anything that works I will except. Even changing the source code of the program is fine

Share Improve this question asked Nov 4, 2014 at 21:40 DactaxxDactaxx 91 silver badge1 bronze badge 2
  • This is extremely broad. Can you post data back to your server via AJAX? Does your program connect to a database already? Do you have external file resources? Have you looked into cookies or local storage? You say Even changing the source code of the program is fine: I can guarantee you that a change to the program is needed to add this feature. – Patrick M Commented Nov 4, 2014 at 21:53
  • Bonus points to anyone who can make this happen without changing the source code. – Raphael Serota Commented Nov 4, 2014 at 22:32
Add a ment  | 

1 Answer 1

Reset to default 5

If you want to do this client-side, your options are basically:

  • local storage
  • cookies

Local storage is probably simplest:

var score = 1;
localStorage.score = 1;

Then later:

var score = parseInt(localStorage.score);

Note that everything you store in local storage is treated as a string. If you have a plex object, you'll have to convert it to JSON and back:

var players = {left:"tarzan", right:"jane"};
localStorage.score = JSON.stringify(players);

Then later:

var players = JSON.parse(localStorage.players);
发布评论

评论列表(0)

  1. 暂无评论