简体   繁体   中英

How do i create a cookie in JavaScript?

I'm trying to create a cookie to hold the;

Name, Email, Phone Number, Job(a selection in a list/text in a field) and The state of two iphone-type toggle buttons then load then all into the page when the user next looks at it,

and am hoplessly stuck. I can't find a website that helps explain it to me clearly enough. Any help at all would be amazing, thanks x

You probably need a plugin like this one: https://github.com/ScottHamper/Cookies

OR include this script

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

Useage:

var selector = $('#name');
$.cookie("thename", selector, { path: '/' });
console.log(selector);

我一直在使用jquery cookie https://github.com/carhartl/jquery-cookie ,这使得对cookie的读写非常容易。

If you know jQuery , you should use this plugin : jquery.cookie

Usage :

Set cookie 1 : $.cookie('the_cookie', 'the_value');

Set cookie 2 : $.cookie('the_cookie', 'the_value', { expires: 7 });

Get cookie : $.cookie('the_cookie');

Delete cookie : $.removeCookie('the_cookie');

EDIT

Let's take this HTML form :

<form method="post" action="somefile.php" id="mygreatform">

    <input type="text" name="name" id="name"/>
    <input type="text" name="email" name="email"/>
    <input type="text" name="phone" name="phone"/>

    <select name="job" id="job">
        <option value="job1">Job 1</option>
        <option value="job2">Job 2</option>
    </select>

</form>

We catch the form submit event in javascript, in order to serialized all input values in one JSON string, and store this string in a cookie :

$('#mygreatform').submit(function()
{
    var formValues = {
        'name' : document.getElementById('name'),
        'email' : document.getElementById('email'),
        'phone' : document.getElementById('phone'),
        'job' : document.getElementById('job')
    };

    // Create JSON string : {"name":"...","email":"...","phone":"...","job":"..."}
    // "..." are all user inputs
    var formValuesStr = JSON.stringify(formValues);

    // expires 14 days from then
    $.cookie('cookie_name', formValuesStr, { expires: 14 });
});

On another page, we will try to read the cookie :

$(document).ready(function()
{
    var formValuesStr = $.cookie('cookie_name');

    if(formValuesStr != null)
    {
        var formValues = JSON.parse(formValuesStr);

        alert('User email : ' + formValues['email']);
    }
});

This is how you can set a cookie using a pure javascript

document.cookie = "cookieName=cookieValue";

The cookie will be set for a current domain. you HAVE to run this code on some server. cookies will not work if you just open a html file in a browser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM