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

I'm trying to store an array of objects in a cookie using JSON.Stringify but I'm having a pro

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745155457a4614092.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信