问题
I have a slight problem in that the string I'm reading from a cookie is broken after the ampersand. So for example the string "hello & world" would just display "hello ". It is a string that is a short code, and converted to something more meaningful using a switch function, and then displayed within a text box. The switch function works fine, but obviously if it is not reading the full string from the cookie in the first place, then it won't be able to locate the short code within the switch function.
I am currently using the following code to read the cookie...
document.example.textfield.value = switchFunction(unescape(coalesce($_GET['example'],readCookie('_cookie'))));
If you need me to supply anymore information then please let me know. This is my first post here, so apologies in advance if anything is wrong or unclear.
Thanks For your help.
EDIT
The switchFunction looks like this..
function SwitchFuntion(Code){
switch(Code){
case 'text & text, Text' : return 'new meaningful text'; break;
}
}
etc....
The readCookie function is like this...
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;
}
回答1:
I think I have run into a similar problem in an ASP.NET MVC app.
When I save a string containing ampersands to a cookie name/value pair it actually gets split into a series of name/value pairs
e.g. attempting to save ("value","cookiedata123&book=2&page=0")
will result in 3 name value pairs being created "value"="cookiedata123"; "book"="2"; and "page"="0"
.
I have resolved this by URL Encoding the value just before writing to the cookie and URL Decoding it as soon as I read it out. In .net the calls look like this:
// Encode
return System.Web.HttpUtility.UrlEncode(cookieData);
// Decode
return System.Web.HttpUtility.UrlDecode(encodedCookieData);
That takes care of any ampersands, equals signs etc that can cause problems. See this post here for info on characters that are allowed in cookies. Allowed characters in cookies
来源:https://stackoverflow.com/questions/4125807/broken-string-in-cookie-after-ampersand-javascript