将表数据保存到Cookie并检索该表及其数据的问题

时间:2018-12-24 02:42:09

标签: javascript cookies

我试图将表数据保存到cookie中,并在以后再次访问它。我的问题与 Set and Load table data with cookie,但无法解决我的问题(我已经尝试过此解决方案,但是没有用)。这是从一个旧的大学工作中来的,但是我现在正在做一个个人项目,但是在cookie方面非常相似。 cookie函数对我的代码进行了很好的注释,但是如果需要更多信息,请告诉我!预先感谢

链接:https://jsfiddle.net/16398101/cq3ob458/

function setCookie() {
//using ~ to seperate values as , and ; are doing weird things to cookies (explained better below)
  document.cookie += '~ expires=Thu, 01 Jan 1970 00:00:01 GMT'; // trying to reset cookie each time we enter this function as table could be saved multiple times per session

  var d = new Date(); //get date
  d.setTime(d.getTime() + (60 * 24 * 60 * 60 * 1000)); // about 2 months in future
  var expires = "expires=" + d.toUTCString();
  var table = document.getElementById("mytab");

  var r = table.rows.length;

  var c = table.rows[0].cells.length;

  var s1 = r + "~" + c + "~"; // get len of rows and cols to add them later
  /* using "~" as "," or ";" made the splitting act weird
                              e.g would add entire cookie into first cell of table*/
  for (var i = 1; i < table.rows.length; i++) {
    for (var j = 0; j < table.rows[i].cells.length; j++) {
      s1 += table.rows[i].cells[j].innerHTML + "~"; //get data from table
    }
  }
  s1 += expires; //add expiration date
  document.cookie = s1;
  console.log("logging s1 " + s1); //cookie looks good until here

}



function getCookie() {
  console.log("In GetCookie");
  var table = document.getElementById("mytab");
  var x = document.cookie;
  console.log("logging x" + x);

  var x1 = x.split("~");

  var r = x1[0];
  var c = x1[1];

  for (var i = 0; i < (r - 2); i++) { // add rows (-2 as already two rows)
    addRow();
  }

  for (var j = 0; j < (c - 4); j++) { // add rows (-4 as already four cols)
    addCol();
  }

  /*   if (x1[0].indexOf("~") > -1) {
      x1[0] = "Student Name";
    }
     */
  var count = 0;
  for (var p = 1; p < table.rows.length; p++) { // row 0 is header therefore ignore
    for (var o = 0; o < table.rows[i].cells.length; o++) { //cols start at 0

      table.rows[p].cells[o].innerHTML = x1[count + 2]; // +2 as 0 and 1 are rows and cols len

      console.log("logging x1[count]" + x1[count]);
      count++;
      add();
    }
  }
}

我在这里和其他站点尝试了几种不同的解决方案,但似乎都没有效果

我希望将表恢复到保存时的状态,但此刻它会用“未定义”或“注”或第一个单元格中的整个cookie填充表(几种不同结果导致失败)解决方案)

注意:代码是用普通js编写的,但是jQuery或其他任何解决方案都可以

2 个答案:

答案 0 :(得分:0)

这是您的另一个主意:

我猜您的数据是“对象”形式,如果是这样,只需使用JSON.stringify(table);。它将返回对象的字符串版本,然后您可以使用document.cookie()window.localStorage()(我更喜欢)将其存储为cookie。而且,当您检索它时,它将采用字符串格式,因此只需使用JSON.parse(objString)即可将其切换回对象。

希望有帮助!

答案 1 :(得分:0)

是否需要将表内容发送到服务器?如果不是,请考虑使用localStorage代替cookie-在需要时从localStorage提取值更加容易。

此外,您可以只存储/恢复表节点的整个innerHTML,而不用建立自己的表内容字符串表示形式。示例:

localStorage.table = document.querySelector('#mytab').innerHTML.trim() // store

document.querySelector('#mytab').innerHTML = localStorage.table // restore