get parameter value from cookie
Hi I have a small problem. Currently I have 2 parameters saved in the browser cookie which ar开发者_StackOverflow中文版e ADV and LOC... Now I have a page with a form and the form got two hidden fields :
<input type="hidden" name="adv" value="" />
<input type="hidden" name="loc" value="" />
I need to get the values of adv and loc from the cookie and save them in the hidden form fields... How can i do this please? Thanks
document.cookie
will get you all the cookies in the following format:
'adv=adv_val; loc=loc_val;'
To get a value from a cookie, you can use this function (from quirksmode):
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
To fill in the hidden fields, you can loop though all the hidden fields, and get their respective cookies:
function hiddenCookies(){
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
var element = inputs[i];
if(element.getAttribute('type') == 'hidden'){
element.value = readCookie(element.name);
}
}
}
And then modify <body>
to have an onload
.
<body onload="hiddenCookies()">
Or with jQuery:
$(function(){
$('input:hidden').each(function(i,v){
v.value = readCookie(v.name);
});
});
You can use this snippet to convert the cookie string into a map.
let cookieMap = document.cookie.split(";").map((str)=>str.split("=")).reduce(reduceToMap(map,curr),{});
function reduceToMap(map,currentArray) {
// convert array to map
map[currArray[0]] = currentArray[1];
return map;
}
What this is doing is essentially the following:
- Splitting the string into an array of strings (of the form "key=value")
- Mapping each string of this array to an array of the form ["key","value"]
- Reducing this array of arrays (of the form [ ["k1","v1"], ["k2","v2"] ]) into a map
Now you can simply access any cookie by doing the following:
let cookieName = "name of the cookie you want to access";
let cookieValue = cookieMap[cookieName];
精彩评论