【发布时间】:2020-12-01 00:47:38
【问题描述】:
我查看了许多 SO,但无法弄清楚如何使用纯 JS 实际完成这项工作。我的问题是我需要向 json 数组添加 2 个不同的 url 并将其存储到 cookie 中以便跨子域访问(我查看了 iframe 本地存储的东西,它不适用于这个应用程序,json 数组将是相当小,所以 4k cookie 限制就足够了)。
现在我有以下内容:
function getProject(){
var url_str = window.location.href;
var ProjectImgId = url_str.split('projectId=')[1];
ProjectImgId = ProjectImgId.split('&')[0];
var UserId = url_str.split('flashId=')[1];
var ImageURL = 'https://project-api.artifactuprising.com/project/' + ProjectImgId + '/thumbnail?user=' + UserId;
var RecentProjects = {"url" : url_str, "img" : ImageURL};
return RecentProjects;
}
以上将在特定页面加载时运行。我希望能够对此执行以下操作:检索任何现有项目,如果 url 上没有匹配项,我想将 RecentProjects 推送到 cookie 数组。
这就是我被难住的地方。我正在关注 w3 School 的 cookie 设置,该设置过去对我有用,但我无法弄清楚如何使用 stringify 和 parse 推送和拉取这些数据。
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 + ";path=/";
}
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 recent = getCookie("yourRecentProjects");
if (recent != "") {
// this is where I would want to parse the JSON and then check if the getProject.url value is in the current cookie json and if it is not, push it.
} else {
recent = getProject();
if (recent != "" && recent != null) {
setCookie("yourRecentProjects", recent, 365);
}
}
}
我很困惑。我已经想出了如何使用本地存储来完成所有这些工作,然后我意识到这在子域中不起作用,所以学习体验很好,但不是解决方案。任何帮助将不胜感激。
【问题讨论】:
标签: javascript arrays json object cookies