Set cookie dan mendapatkan cookie dengan JavaScript

I'm mencoba untuk mengatur cookie tergantung pada file CSS yang saya pilih di HTML saya. Saya punya sebuah form dengan sebuah daftar pilihan, dan file CSS yang berbeda sebagai nilai-nilai. Ketika saya memilih sebuah file, itu harus disimpan di cookie selama sekitar satu minggu. Waktu berikutnya anda membuka file HTML anda, itu harus menjadi file sebelumnya anda've dipilih.

Kode JavaScript:

function cssLayout() {
    document.getElementById("css").href = this.value;
}

function setCookie(){
    var date = new Date("Februari 10, 2013");
    var dateString = date.toGMTString();
    var cookieString = "Css=document.getElementById("css").href" + dateString;
    document.cookie = cookieString;
}

function getCookie(){
    alert(document.cookie);
}

HTML:

<form>
    Select your css layout:<br>
    <select id="myList">
        <option value="style-1.css">CSS1</option>
        <option value="style-2.css">CSS2</option>  
        <option value="style-3.css">CSS3</option>
        <option value="style-4.css">CSS4</option>
    </select>
</form>
Mengomentari pertanyaan (5)

Saya menemukan kode berikut untuk menjadi jauh lebih sederhana dari apa pun:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    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,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

Sekarang, pemanggilan fungsi

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Sumber - http://www.quirksmode.org/js/cookies.html

Mereka diperbarui halaman hari ini sehingga segala sesuatu di halaman harus terbaru dari sekarang.

Komentar (22)

Ini adalah banyak banyak lebih baik referensi dari w3schools (paling mengerikan referensi web yang pernah dibuat):

Contoh yang berasal dari referensi ini:

// sets the cookie cookie1
document.cookie =
 'cookie1=test; expires=Fri, 19 Jun 2020 20:47:11 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie =
 'cookie2=test; expires=Fri, 19 Jun 2020 20:47:11 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

Mozilla referensi bahkan telah mengirimkan cookie perpustakaan yang dapat anda gunakan.

Komentar (14)

I'm yakin pertanyaan ini harus memiliki lebih umum menjawab dengan beberapa kode yang dapat digunakan kembali bekerja dengan cookie sebagai pasangan kunci-nilai.

Cuplikan ini diambil dari MDN dan mungkin lebih terpercaya. Ini adalah UTF-aman objek untuk bekerja dengan cookie:

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Mozilla telah beberapa tes untuk membuktikan ini bekerja di semua kasus.

Ada alternatif snippet di sini:

Komentar (6)

Check [JavaScript Cookie di W3Schools.com][1] untuk menetapkan dan mendapatkan cookie nilai-nilai via JS.

Hanya menggunakan setCookie dan getCookie metode yang disebutkan di sana.

Jadi, kode akan terlihat seperti ini:


<script>
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function cssSelected() {
    var cssSelected = $('#myList')[0].value;
    if (cssSelected !== "select") {
        setCookie("selectedCSS", cssSelected, 3);
    }
}

$(document).ready(function() {
    $('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
    --Select--
    CSS1
    CSS2
    CSS3
    CSS4
Komentar (9)