Jquery Cookie 插件 - 多个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6417140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:49:56  来源:igfitidea点击:

Jquery Cookie plugin - multiple values?

jquerycookies

提问by Stewie Griffin

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

我正在使用流行的 jquery Cookie 插件https://github.com/carhartl/jquery-cookie想知道如何设置和读取具有多个值的 cookie?或者也许可以添加/删除该 cookie 的值?

$.cookie("MyTestCookie", email, { expires: 10 });

$.cookie("MyTestCookie", email, { expires: 10 });

I want to add username to the same cookie

我想将用户名添加到同一个 cookie

Update: just an example in .Net Storing multiple values in cookies

更新:只是 .Net 中的一个示例在 cookie 中存储多个值

回答by Kiliman

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.

如果要设置具有多个值或“子键”的 cookie 并使其可从 .NET 读取,则需要将子键存储为名称-值对,格式类似于查询字符串。您可以使用 jQuery.param() 方法将 Javascript 对象转换为查询字符串。

var obj = { email: '[email protected]', 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/

编辑:我创建了一个测试页面来显示在服务器和客户端上读取/写入多值 cookie。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.
  • 您需要注意转义和取消转义子项。这样任何嵌入的 = 和 & 都被正确处理
  • 读取和写入 jquery cookie 时,请使用选项 { raw: true } 以免双重转义。
  • 我写了一个 $.deparam 函数,它将 name=value&name2=value2 字符串转换为 javascript 对象 { name: value, name2: value2 }
  • 最后一件事,jquery cookie 插件不会覆盖同名的 cookie,它只是将它附加到当前的 cookie 集合中。此时,重写插件以支持子键和修改现有 cookie 可能会更好。

Anyway hope this helps.

无论如何希望这会有所帮助。

Here is Default.aspx

这是 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

默认.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var cookie = new HttpCookie("MyTestCookie");
        cookie["email"] = HttpUtility.UrlEncode("[email protected]");
        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]) : "";
}

回答by Schahriar SaffarShargh

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

即使不建议您仍然可以向 cookie 添加多个值并自己进行处理。

(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)

(这将减少浏览器中保留的 cookie 数量,但由于现代浏览器旨在处理大量 cookie,因此不会对加载速度产生任何影响)

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.

您可以使用循环添加您的值,并使用像“ %”这样的特殊字符将它们分开,您可以使用您喜欢的任何加密方法处理您的字符串,并将所有内容保存为一个 cookie。

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


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

稍后您可以使用SPLIT函数将代码转换为正确的数组值:

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.

这是您可以用来处理 cookie 的最合适的方法,其他方法会稍微减慢页面速度。

回答by uzername_not_found

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

试试这个: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

快速使用:

创建 - 创建 cookie

检查 - 检查存在

验证 - 如果 JSON 验证 cookie 值

check_index - 验证 JSON 中是否存在索引

read_values - 读取 cookie 值作为字符串

read_JSON - 读取 cookie 值作为 JSON 对象

read_value - 读取存储在 JSON 对象中的索引值

replace_value - 从存储在 JSON 对象中的指定索引中替换值

remove_value - 删除存储在 JSON 对象中的值和索引

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");

回答by Matt

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

我在 cookie 中得到了这个值

a%3Dtest%26b%3Dbest

a%3Dtest%26b%3Dbest

So to get something like

所以要得到类似的东西

a=test&b=best

a=测试&b=最佳

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

你需要在 $.cookie() 之前添加这一行

$.cookie.raw = true;