none
自定义js对象怎么保存到cookie?怎么读取? RRS feed

  • 问题

  • function njPaiMing() { this.ID, this.Name, this.LiRunBi, this.UserPayPrice, this.SortLiRun, this.SortUserPayPrice }

    var myobj=new njPaiMing();

    myobj.ID=1;

    myobj.Name='alian';

    就像上面的对象,怎么保存到cookie中?然后又怎么读取呢?

    开心了就笑,不开心了就过会儿再笑

    2013年10月9日 6:53

答案

  • Cookie只能保存字符串,要不你尝试用JSON格式保存对象,大不了以后用js在客户端解析复原即可。

    Click For donating:Free Rice For the poor
    For spamming-sender issues, you can either report it at Microsoft Spamming Issue, or just find "Report Spam Here+Number" at Forum Issue;You can also find "Verify Your Account+Number" at "Forum Issue", where you can submit to be confirmed to paste links or images.
    For more things to talk about? StackOverFlow is your choice.

    • 已标记为答案 NewJoin 2013年10月11日 7:32
    2013年10月9日 9:42

全部回复

  • Cookie只能保存字符串,要不你尝试用JSON格式保存对象,大不了以后用js在客户端解析复原即可。

    Click For donating:Free Rice For the poor
    For spamming-sender issues, you can either report it at Microsoft Spamming Issue, or just find "Report Spam Here+Number" at Forum Issue;You can also find "Verify Your Account+Number" at "Forum Issue", where you can submit to be confirmed to paste links or images.
    For more things to talk about? StackOverFlow is your choice.

    • 已标记为答案 NewJoin 2013年10月11日 7:32
    2013年10月9日 9:42
  • 因为cookies只能存储字符串,所以你需要将你的对象连接成 字符串,在读取时在分隔开实例化成你所要的对象。

    你能到w3school 学习一下 JavaScript Cookies ,那里也有一些教程实例:

    设置cooike

    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;
     }

    读取cooike

    function getCookie(c_name)
    {
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1)
      {
       c_start = c_value.indexOf(c_name + "=");
      }
    if (c_start == -1)
      {
       c_value = null;
      }
    else
      {
      c_start = c_value.indexOf("=", c_start) + 1;
      var c_end = c_value.indexOf(";", c_start);
      if (c_end == -1)
      {
     c_end = c_value.length;
    }
    c_value = unescape(c_value.substring(c_start,c_end));
    }
    return c_value;
    }

    读下面的链接了解更多信息:

    http://www.w3schools.com/js/js_cookies.asp


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2013年10月11日 1:23
    版主