gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:31:21 26 4
gpt4 key购买 nike

我正在尝试使用 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);
}
<!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 -> 将新对象添加到数组 -> 再次对其进行字符串化

谢谢

最佳答案

您使用此代码:

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 而不是包含它的数组。

因此,下次当您尝试推送另一条评论时,您将无法推送。

请尝试以下操作:

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

关于javascript - 如何使用 json.stringify 在 cookie 中正确存储对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28269179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com