如何使用json.stringify在cookie中正确存储对象数组?

时间:2015-02-01 23:26:37

标签: javascript jquery json parsing stringify

我试图使用JSON.Stringify在cookie中存储一个对象数组,但是当我解析cookie并尝试将一个新对象推送到数组然后将其字符串化时,我遇到了问题再次。它告诉我comments.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);
}
&#13;
<!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> 
&#13;
&#13;
&#13;

可能是什么问题? 我只是想解析我的cookie - &gt;将新对象添加到数组 - &gt;再次串化

由于

2 个答案:

答案 0 :(得分:1)

这是你的问题:

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

你可能打算做

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

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

答案 1 :(得分:1)

您使用此代码:

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