【问题标题】:How to properly store an array of objects in a cookie using json.stringify?如何使用 json.stringify 在 cookie 中正确存储对象数组?
【发布时间】:2015-03-31 21:27:01
【问题描述】:

我正在尝试使用 JSON.Stringify 将对象数组存储在 cookie 中,但是当我解析 cookie 并尝试将新对象推送到数组以再次对其进行字符串化时遇到问题。它告诉我 cmets.push 不是一个函数。

var comments = [];
var myData = 0;

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function checkCookie() {
    var commentAux = getCookie("myComments");
    if (commentAux != "") {
        //alert("Welcome again " + user);
        return true;
    } else {
        return false;
    }
}

function validateComment() {
	var x = document.forms["commentForm"]["commentSection"].value;
	if (x == null || x == "") {
		alert("There's nothing to comment, write something to proceed.");
		return false;
	} else {
		var comment = {
			firstName:"Name",
			lastName:"Surname",
			text:x
		};
		if (checkCookie() == false) {
			setCookie("myComments", JSON.stringify(comment), 1);
		} else {
			myData = getCookie("myComments");
			comments = JSON.parse(myData);
			alert(comments);
			comments.push(comment);
			setCookie("myComments", JSON.stringify(comments), 1);
		}
	}
	alert(comments.length);
}
<!DOCTYPE html>
<html>
	<head>
		<title>Facebook Simulator by Azael Alanis</title>
		<link rel="stylesheet" type="text/css" href="style.css">
		<script src="javascript.js"></script>
	</head>
	<body>
		<img src="facebook-banner.png" alt="Facebook-Banner" style="height:100px;width:800px">
		<div id="section">
			<form name="commentForm" onsubmit="validateComment()">
				<input type="text" name="commentSection" placeholder="What's on your mind?"><button class="buttonText">Enviar</button>
			</form> 
		</div>
	</body>
</html> 

可能是什么问题? 我只想解析我的 cookie -> 将新对象添加到数组 -> 再次对其进行字符串化

谢谢

【问题讨论】:

  • 评论看起来像一个对象,而不是一个数组。
  • 有办法把它转成数组吗?
  • 如果您没有使用服务器上的cookie,请不要使用cookie...使用本地存储。

标签: javascript jquery json parsing stringify


【解决方案1】:

这是你的问题:

comments = JSON.parse(myData);
comments.push(comment);

你可能打算这样做

var comment = JSON.parse(myData);
comments.push(comment);

由于JSON.parse(myData) 返回一个评论对象。

【讨论】:

    【解决方案2】:

    您使用此代码:

    var comment = { /* ... */ };
    if (checkCookie() == false) {
        setCookie("myComments", JSON.stringify(comment), 1);
    } else {
        comments = JSON.parse(getCookie("myComments"));
        comments.push(comment);
        setCookie("myComments", JSON.stringify(comments), 1);
    }
    

    问题在于,最初您存储对象 comment 而不是包含它的数组。

    因此,下次当你尝试推送另一个comment 时,你就不能了。

    请尝试以下方法:

    var comment = { /* ... */ };
    if (checkCookie() == false) {
        setCookie("myComments", JSON.stringify([comment]), 1); // <-- array
    } else {
        comments = JSON.parse(getCookie("myComments"));
        comments.push(comment);
        setCookie("myComments", JSON.stringify(comments), 1);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-20
      • 1970-01-01
      • 2019-12-16
      • 2011-03-21
      • 1970-01-01
      • 2016-05-07
      • 2011-09-30
      • 2021-12-28
      • 1970-01-01
      相关资源
      最近更新 更多