Create array in cookie with javascript

后端 未结 9 909
-上瘾入骨i
-上瘾入骨i 2020-12-08 10:32

Is it possible to create a cookie using arrays?

I would like to store a[0]=\'peter\', a[\'1\']=\'esther\', a[\'2\']=\'john\' i

9条回答
  •  难免孤独
    2020-12-08 11:07

    You can save a lot of data within a single cookie and return it as an array, try this

      function setCookie(cookieKey, cookieValue) {
            var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
            var idPurchase = cookie.split(",")
            idPurchase.push(cookieValue)
            document.cookie = cookieKey+"=" + idPurchase
            console.log("Id das compras efetuadas :",idPurchase)
            $("#purchases_ids option:last").after($(''))
        }
        checkCookie()
        function checkCookie() {
            var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
            var idPurchase = cookie.split(",")
            console.log("Id das compras efetuadas :",idPurchase)
            for (i = 1; i < idPurchase.length; i++) {
            $("#purchases_ids option:last").after($(''))
            }
            purchases_ids.addEventListener("change",changeSpeed)
        }
    

    in this project that I created I store values ​​in arrays, codePen is not allowing the storage of cookies, but in the example below you can get a complete picture, just study the implementation

    Github project

    Open in Gitpod

提交回复
热议问题