简体   繁体   中英

Create a cookie with a non url encoded value using JQuery and the Cookie plugin

I am creating a cookie on the client side and adding 3 string values in it separated by commas. The string have special characters. The problem is when I am fetching the value of the cookie in my code behind, the cookie has value as follows:-

4%2CHealth%20Related%2C%2Fmysite%2FYourKB%2FHealth-Related

I want to get rid of these % signs and values.. Is replacing these characters the only way? How can I make my cookie not have these values and just simple text with some special characters?

edit 1

I am creating cookie like this now but still the problem persists. Please help me out.

$.cookie('MyCookie', unescape(myString), { path: '/' }, { expires: 30 });

I know this thread is ancient, but I just ran into this and came across the raw setting . Setting it to true fixed the issue for me.

For completeness those %xx characters are url encodings of certain characters that are not allowed in URLs.

So: %2C is a comma and %2F is a forward slash.

Taking that into account, where are you checking the value of the cookie again?

This code works and gives you the correct value as an alert:

<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"> </script>
    <script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
  </head>
  <body>
<script language="javascript">
<!--
$(function(){
  var myString = '4%2CHealth%20Related%2C%2Fmysite%2FYourKB%2FHealth-Related';
  $.cookie('MyCookie', unescape(myString) );
  alert($.cookie('MyCookie'));
    });
-->
</script>
  </body>
</html>

So basically your code above should work, but if you are checking on the server make sure your server-side technology decodes the value as well. In ASP.NET this is done automatically when you call Request.Cookies["MyCookie"].Value but AFAIK the browser will transmit it only as a url encoded value so it has to be decoded again on the server.

HTH Alex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM