浏览器关闭时正在删除数据。

时间:2016-03-14 22:09:48

标签: javascript

我有这个游戏板存储锦标赛的结果,我无法弄清楚为什么在浏览器关闭时数据(通过下拉菜单输入的游戏结果)会被删除。只要服务器正在运行,我的结果是否有办法持续存在?

结果在main.js

中显示如下
$.post('/postScores', results, function(scores){
  var gameBoard = "";
      for(var j=0;j<scores.length;j++){
          gameBoard+= '<tr>';

          for(var k=0;k<5;k++){             
            gameBoard += '<td>'+scores[k][j]+'</td>';
          }
          gameBoard += '</tr>';
      }

      $("#grid").append(gameBoard);

  });

我的分数存储在server.js中,如下所示:

 app.post("/postScores", function(req , res){ 
    res.setHeader("Content-Type", "application/json");

    var results = [
  [ "", "team1", "team2", "team3", "team4"],
  ["team1", "x", req.body.e, req.body.h, req.body.k],
  ["team2", req.body.b, "x", req.body.i, req.body.l],
  ["team3", req.body.c, req.body.f, "x", req.body.m],
  ["team4", req.body.d, req.body.g, req.body.j, "x" ]
  ];

   res.json(results);
   res.end();

});

完整计划:https://jsfiddle.net/Amidi/egp1hst3/10/

2 个答案:

答案 0 :(得分:4)

当您使用javascript修改当前查看的页面时,这些更改本质上是临时设计。下次加载同一页面时,它将再次从浏览器加载HTML结构并将其呈现在原始状态中。这确实很有意义,因为您希望浏览器呈现服务器发送给您的页面而不是其他内容。

如果要对UI进行永久性更改,则需要将状态存储在服务器上并包含html响应中的更改,或者在客户端上保存状态(例如,在cookie或localstorage中),然后还要加载页面后,从那里应用修改。

答案 1 :(得分:2)

Use localStorage like this.

var yourData = '';
localStorage.setItem('gameData',yourData);

to retrieve

var retrievedData = localStorage.getItem('gameData');

Keep in mind that you cannot store arrays in localStorage, so you will have to stringify before you save to localStorage and parse when you retrieve the data. Also keep in mind that you cannot store more than 5MB in localStorage, which shouldn't be a problem for you. If you want persistence beyond the browser's cache, you will have to use a database of some kind.