Jquery Cookie plugin - multiple values?

后端 未结 4 514
长情又很酷
长情又很酷 2020-12-18 00:18

I am using popular jquery Cookie plugin https://github.com/carhartl/jquery-cookie Wonder how to set and read a cookie with multiple values? Or maybe it\'s possible to add/re

相关标签:
4条回答
  • 2020-12-18 00:45

    If you want to set a cookie that has multiple values or "subkeys" and have them readable from .NET, you need to store the subkey as name-value pairs formatted like a querystring. You can use the jQuery.param() method to convert a Javascript object into a querystring.

    var obj = { email: 'jdoe@example.com', username: 'jdoe' };
    $.cookie("MyTestCookie", $.param(obj), { expires: 10 });
    

    Then on the server, you can access the values as:

    var email = Request.Cookies["MyTestCookie"]["email"];
    var username = Request.Cookies["MyTestCookie"]["username"];
    

    EDIT: I created a test page to show reading/writing multi-value cookies both on the server and client. http://www.systemex.net/Cookies/

    NOTES:

    • You need to take care of escaping and unescaping the subkeys. This way any embedded = and & are handled correctly
    • When reading and writing jquery cookies, use option { raw: true } so it doesn't double escape.
    • I wrote a $.deparam function that will convert a name=value&name2=value2 string into a javascript object { name: value, name2: value2 }
    • One last thing, the jquery cookie plugin does not overwrite a cookie with the same name, it simply appends it to the current cookie collection. At this point, it would probably be better to rewrite the plugin to support subkeys and modifying existing cookies.

    Anyway hope this helps.

    Here is Default.aspx

    <h1>Get Cookie From Server:</h1>
    <ul>
    <li>Email: <%= GetCookie("MyTestCookie", "email")%></li>
    <li>Username: <%= GetCookie("MyTestCookie", "username")%></li>
    </ul>
    <h1>Get Cookie From Client:</h1>
    <ul>
    <li>Email: <span class="cookie" data-name="MyTestCookie" data-key="email" /></li>
    <li>Username: <span class="cookie" data-name="MyTestCookie" data-key="username" /></li>
    <li>Raw: <span id="raw" /></li>
    </ul>
    <h1>Set Cookie From Client:</h1>
    <ul>
    <li>Email: <input type="text" name="email" value="" /></li>
    <li>Username: <input type="text" name="username" value="" /></li>
    </ul>
    <input type="submit" value="Submit" />
    
    <script>
    
        $(function () {
            $(".cookie").each(function (index) {
                var name = $(this).data('name');
                var key = $(this).data('key');
                var cookie = $.deparam($.cookie(name, { raw: true }));
    
                $(this).html(cookie[key]);
            });
            $('#raw').text(escape($.cookie("MyTestCookie"), { raw: true }));
    
    
            $("form").submit(function () {
                var o = {};
                o.email = $('input[name=email]').val();
                o.username = $('input[name=username]').val();
                var value = $.param(o);
                var cookie = $.cookie('MyTestCookie', value, { raw: true });
                return true;
            });
        });
    
        jQuery.deparam = function (params) {
            var o = {};
            if (!params) return o;
            var a = params.split('&');
            for (var i = 0; i < a.length; i++) {
                var pair = a[i].split('=');
                o[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
            }
            return o;
        }
    
    </script>
    

    Default.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            var cookie = new HttpCookie("MyTestCookie");
            cookie["email"] = HttpUtility.UrlEncode("jdoe@example.com");
            cookie["username"] = HttpUtility.UrlEncode("jdoe&123");
            Response.Cookies.Add(cookie);
        }
    }
    
    public string GetCookie(string name, string key)
    {
        var cookie = Request.Cookies[name];
        return cookie != null ? HttpUtility.UrlDecode(cookie[key]) : "";
    }
    
    0 讨论(0)
  • 2020-12-18 00:58

    When I was using the

    var obj = { a: 'test', b: 'best' };
    $.cookie("MyCookie", $.param(obj), { expires: 10 });
    

    I was getting this value in the cookie

    a%3Dtest%26b%3Dbest

    So to get something like

    a=test&b=best

    you need to add this line before $.cookie()

    $.cookie.raw = true;
    
    0 讨论(0)
  • 2020-12-18 01:03

    Even though it's not advised you still can add multiple values to a cookie and do the processing yourself.

    (This will reduce the amount of cookies kept in the browser but since modern browsers are designed to process huge loads of cookies it wouldn't do anything to the speed of loading)

    You can add your value using a loop and separate them using a special character like '%' and you can process your string on any encryption method you prefer and save all as one single cookie.

    var setofcookies = username + "%" + password + "%" + email;
    $.cookie("MyTestCookie", setofcookies, { expires: 10 });
    

    Later you can use the SPLIT function to get the code into proper array value:

    var cookie = $.cookie('MyTestCookie')
    var mycookies = cookie.split("%");
    document.write(mycookies[0]);
    

    This is the most appropriate method you can use to process cookies, other methods will slightly slow down the page.

    0 讨论(0)
  • 2020-12-18 01:09

    Try this one: https://github.com/tantau-horia/jquery-SuperCookie

    Quick Usage:

    create - create cookie

    check - check existance

    verify - verify cookie value if JSON

    check_index - verify if index exists in JSON

    read_values - read cookie value as string

    read_JSON - read cookie value as JSON object

    read_value - read value of index stored in JSON object

    replace_value - replace value from a specified index stored in JSON object

    remove_value - remove value and index stored in JSON object

    Just use:

    $.super_cookie().create("name_of_the_cookie",name_field_1:"value1",name_field_2:"value2"});
    $.super_cookie().read_value("name_of_the_cookie","name_field_1");
    
    0 讨论(0)
提交回复
热议问题