2016-12-05 36 views
0

嗨我有cookie的序列化params的价值。如何使用jquery更新序列化的Cookie值?

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

现在我必须更新名称= praveenkumar,年龄= 24,东西= NULL这个cookie字符串。如果value为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的大小变得更大,我会关心性能。

回答

0

太复杂了。试试这个:

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

打开序列化的字符串到基于this answer一个对象

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

。现在,你可以操纵的对象

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

保存t他更新cookie值

$.cookie('criteria', criteria); 

我不明白有关性能的关注,你不应该期待一个浏览器,允许在Cookie超过4096个字节。如果性能和大小是一个问题,你应该使用localStorage。它比Cookie快得多,容量以MB为单位(因浏览器而异)。

+0

@davidkonard这真的很有帮助。性能事件是存储在cookie中的参数数量可能增加,通过每个参数枚举可能会花费更多。 – Praveenkumar