最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to properly store an array of objects in a cookie using json.stringify? - Stack Overflow

programmeradmin1浏览0评论

I'm trying to store an array of objects in a cookie using JSON.Stringify but I'm having a problem when I parse the cookie and try to push a new object to the array to then stringify it again. It tells me that ments.push is not a function.

var ments = [];
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 mentAux = getCookie("myComments");
    if (mentAux != "") {
        //alert("Wele again " + user);
        return true;
    } else {
        return false;
    }
}

function validateComment() {
	var x = document.forms["mentForm"]["mentSection"].value;
	if (x == null || x == "") {
		alert("There's nothing to ment, write something to proceed.");
		return false;
	} else {
		var ment = {
			firstName:"Name",
			lastName:"Surname",
			text:x
		};
		if (checkCookie() == false) {
			setCookie("myComments", JSON.stringify(ment), 1);
		} else {
			myData = getCookie("myComments");
			ments = JSON.parse(myData);
			alert(ments);
			ments.push(ment);
			setCookie("myComments", JSON.stringify(ments), 1);
		}
	}
	alert(ments.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="mentForm" onsubmit="validateComment()">
				<input type="text" name="mentSection" placeholder="What's on your mind?"><button class="buttonText">Enviar</button>
			</form> 
		</div>
	</body>
</html> 

I'm trying to store an array of objects in a cookie using JSON.Stringify but I'm having a problem when I parse the cookie and try to push a new object to the array to then stringify it again. It tells me that ments.push is not a function.

var ments = [];
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 mentAux = getCookie("myComments");
    if (mentAux != "") {
        //alert("Wele again " + user);
        return true;
    } else {
        return false;
    }
}

function validateComment() {
	var x = document.forms["mentForm"]["mentSection"].value;
	if (x == null || x == "") {
		alert("There's nothing to ment, write something to proceed.");
		return false;
	} else {
		var ment = {
			firstName:"Name",
			lastName:"Surname",
			text:x
		};
		if (checkCookie() == false) {
			setCookie("myComments", JSON.stringify(ment), 1);
		} else {
			myData = getCookie("myComments");
			ments = JSON.parse(myData);
			alert(ments);
			ments.push(ment);
			setCookie("myComments", JSON.stringify(ments), 1);
		}
	}
	alert(ments.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="mentForm" onsubmit="validateComment()">
				<input type="text" name="mentSection" placeholder="What's on your mind?"><button class="buttonText">Enviar</button>
			</form> 
		</div>
	</body>
</html> 

What could be the problem? I just want to parse my cookie -> add new object to array -> stringify it again

Thanks

Share Improve this question asked Feb 1, 2015 at 23:26 Azael AlanisAzael Alanis 231 silver badge5 bronze badges 3
  • 2 Comments seems like an object, not an array. – Shomz Commented Feb 1, 2015 at 23:30
  • There's a way to convert it to array? – Azael Alanis Commented Feb 1, 2015 at 23:39
  • If you are not using the cookie on the server, do not use a cookie...Use local storage. – epascarello Commented Feb 1, 2015 at 23:53
Add a ment  | 

2 Answers 2

Reset to default 4

You use this code:

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

The problem is that initially you store the object ment instead of an array containing it.

Therefore, the next time, when you attempt to push another ment, you can't.

Try the following instead:

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

This is your problem:

ments = JSON.parse(myData);
ments.push(ment);

You probably meant to do

var ment = JSON.parse(myData);
ments.push(ment);

Since JSON.parse(myData) returns a ment object.

发布评论

评论列表(0)

  1. 暂无评论