Jquery Cookie插件 - 多个值? [英] Jquery Cookie plugin - multiple values?

查看:314
本文介绍了Jquery Cookie插件 - 多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



$。cookie(MyTestCookie,电子邮件,{expires:10});



我想为同一个Cookie添加用户名



更新: =http://stackoverflow.com/questions/1173729/storing-multiple-values-in-cookies>在Cookie中存储多个值

解决方案

如果你想设置一个具有多个值或子键的cookie,并让它们可以从.NET读取,你需要存储子键作为名称 - 值对格式化的查询字符串。您可以使用jQuery.param()方法将Javascript对象转换为查询字符串。

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

然后在服务器上,您可以访问以下值:

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

编辑:我创建了一个测试页面来显示在服务器上读取/客户。 http://www.systemex.net/Cookies/



注意:




  • 您需要注意转义和取消转义子键。这样,任何嵌入的=和&

  • 在阅读和编写jquery Cookie时,使用选项{raw:true},以避免双重转义。

  • $ .deparam函数,将name = value& name2 = value2字符串转换为javascript对象{name:value,name2:value2}

  • 最后一件事,jquery cookie插件覆盖具有相同名称的cookie,它只是将它附加到当前cookie集合。在这一点上,最好重写插件以支持子项并修改现有的Cookie。



无论如何希望这有帮助。 / p>

这里是Default.aspx

 < h1>服务器:< / h1> 
< ul>
< li>电子邮件:<%= GetCookie(MyTestCookie,email)%>< / li&
< li>用户名:<%= GetCookie(MyTestCookie,username)%>< / li&
< / ul>
< h1>从客户端获取Cookie:< / h1>
< ul>
< li>电子邮件:< span class =cookiedata-name =MyTestCookiedata-key =email/>< / li&
< li>用户名:< span class =cookiedata-name =MyTestCookiedata-key =username/&
< li>原始:< span id =raw/>< / li>
< / ul>
< h1>设置来自客户端的Cookie:< / h1>
< ul>
< li>电子邮件:< input type =textname =emailvalue =/>< / li>
< li>用户名:< input type =textname =usernamevalue =/>< / li>
< / ul>
< input type =submitvalue =Submit/>

< script>

$(function(){
$(。cookie)每个函数(索引){
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 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]):;
}


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/remove values for that cookie?

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

I want to add username to the same cookie

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

解决方案

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]) : "";
}

这篇关于Jquery Cookie插件 - 多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆