【发布时间】:2017-02-23 17:03:17
【问题描述】:
我想要完成的事情:
当按下 href 时,我会调用 saveItem() 函数。它被称为如下:
<a href="#" class="save-product" onclick="saveItem('savedList', '<?php echo get_the_ID();?>', 90)">
savedList = 我的 cookie 的名称
get_the_ID() = 一个 wordpress 函数,用于获取当前的 ID 帖子、'185' 等。
90 = cookie 过期的天数
调用 saveItem() 时,它会检查名称为 savedList 的 cookie 是否已存在。如果没有,它会创建一个具有该名称的 cookie 并添加通过参数传递的值(当前帖子的 id)。
当此 cookie 存在时,我想向该 cookie 添加一个 id,分隔符将是 ;,这样我就可以 - 在另一个页面中通过该 cookie 的列表显示产品列表。
所以我的 cookie 有 "185" 。当我添加一个新 ID 时,例如“65”,我希望我的 cookie 变为“185;65”
我的问题是它没有按预期工作。奇怪的是,如果我在console.log("New Value Is : " + newValue); 上看到它显示“185;65”但是
console.log(mNameList); 再次只显示“185”。
要检查我使用的 cookie 的值:
print_r($_COOKIE['savedList']);
以下功能:
saveItem():
function saveItem(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
// Get Cookie
var mNameList = getCookie(name);
// If cookie is empty - doesn't exist then create it and put the value given
if (mNameList == "") {
document.cookie = name + "=" + value + expires + "; path=/";
} else {
// If cookie exists, check if it has already this value, if it doesn't then add oldvalue + new value to that cookie.
if(mNameList !== value){
var newValue = mNameList + ';' + value; // "185;65"
document.cookie = name + "=" + newValue + expires + "; path=/";
console.log("New Value Is : " + newValue);
var mNameList = getCookie(name); // Το check current cookie get it again
console.log(mNameList); // Show it - here it shows "185"
}
else{
// Value already exists in cookie - don't add it
console.log("Are same - mNameList->" + mNameList + " | currentID->" + value);
}
}
}
Getcookie();
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
【问题讨论】:
标签: javascript php wordpress cookies