doujia3441 2017-02-23 08:35
浏览 16
已采纳

设置cookie无法按预期工作

What i am trying to accomplish :

When a href is pressed i call the saveItem() function. It is called as below :

<a href="#" class="save-product" onclick="saveItem('savedList', '<?php echo get_the_ID();?>', 90)">

savedList = the name of my cookie

get_the_ID() = A wordpress function to get the current's ID post, '185' etc.

90 = the days for the cookie to expire

When saveItem() is called, it checks if a cookie with name savedList already exists. If it doesn't, it creates a cookie with that name and adds the value which is passed through the parameter(the id of current post). When this cookie exists, i want to add to that cookie one more id and the delimiter would be ; so i can - in another page show a list of products through that cookie's list.

So my cookie has "185" . When i add a new ID, for example "65", i want my cookie to become "185;65"

My problem is that it doesn't work as expected. The weird thing is that if i see on the console.log("New Value Is : " + newValue); it shows "185;65" but console.log(mNameList); shows only "185" again.

To check my cookie's value i use :

print_r($_COOKIE['savedList']);

Functions below :

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 "";
    }
  • 写回答

2条回答 默认 最新

  • doulan3966 2017-02-23 09:03
    关注

    Ok so the problem was in the delimiter and in my code too - the way i was checking if ID already exists was wrong but the below works.

    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();
            }
    
            var mNameList = getCookie(name);
    
            if (mNameList == "") {
                document.cookie = name + "=" + value + expires + "; path=/";
            } else {
    
                var doesItemExists = false;
                var partsOfStr = mNameList.split('-');
    
                for(var i =0; i < partsOfStr.length; i++){
                    if(partsOfStr[i] == value)
                        doesItemExists = true;
                }
    
                if(!doesItemExists){
                    var newValue = mNameList + '-' + value;
                    document.cookie = name + "=" + newValue + expires + "; path=/";
                    console.log("New Value Is : " + newValue);
                }
                else{
                    console.log("Are same - mNameList->" + mNameList + "  |   currentID->" + value);
                }
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题