【问题标题】:How to update serialized Cookie Value using jquery?如何使用 jquery 更新序列化的 Cookie 值?
【发布时间】:2017-04-19 10:32:29
【问题描述】:

您好,我有一个具有序列化参数值的 cookie。

i.e)criteria = "name=praveen&age=25&studying=false&working=true&something=value"

现在我必须在这个 cookie 字符串中更新 name = praveenkumar,age = 24,something = null。如果值为 null(something = null),则应将其从 cookie 中删除。以下是我正在使用的代码。

updateCookie({'name':'praveenkumar','age':24,'something':null})
var updateCookie = function(params) {
// split the cookie into array
var arr = $.cookie('criteria').split("&");
//loop through each element
for(var i = arr.length - 1; i >= 0; i--) {
  // getting the key i.e) name,age
  var key = arr[i].split("=")[0];
  // if the key is in given param updating the value
  if( key in params) {
    // if vale null remove the element from array or update the value
    if(params[key] !== null) {
      arr[i] = key+"="+params[key];
    }
    else {
      arr.splice(i, 1);
    }
  }
}
// join array by & to frame cookie string again
$.cookie('criteria' , arr.join("&"));

};

它正在工作。但是如果 cookie 的大小变大,我会担心性能。

【问题讨论】:

    标签: javascript jquery arrays cookies serialization


    【解决方案1】:

    太复杂了。试试这个:

    var criteria = "name=praveen&age=25&studying=false&working=true&something=value";
    

    将序列化的字符串变成对象

    var obj = JSON.parse('{"' + decodeURI(criteria)
                               .replace(/"/g, '\\"')
                               .replace(/&/g, '","')
                               .replace(/=/g,'":"') 
                      + '"}')
    

    基于this answer。现在你可以操作对象了

    obj.studying = null;
    

    从对象中移除 null

    for (prop in obj) {
      if (obj[prop] == null) delete obj[prop]
    }
    

    使用 jQuery 的$.param 将修改后的对象作为序列化字符串获取

    criteria = $.param(obj);
    

    == name=praveen&age=25&working=true&something=value

    保存更新的cookie值

    $.cookie('criteria', criteria);
    

    我不理解对性能的担忧,您永远不应该期望浏览器在 cookie 中允许超过 4096 个字节。如果性能和大小是一个问题,您应该使用 localStorage。它比 cookie 快得多,并且容量以 MB 为单位(因浏览器而异)。

    【讨论】:

    • @davidkonard 这真的很有帮助。性能问题是cookie中存储的参数数量可能会增加,通过每个参数枚举可能会花费更多。
    猜你喜欢
    • 2021-08-15
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多