In the process of website development, whether the front-end uses JavaScript or the backend uses server-side languages to process cookies, It is a skill that must be mastered by web developers.
I believe that it is often used in the development process. However, we still need to think about how to make the front-end and backend get the same cookie at the same time.
I will introduce the following points:
1. First, we use js to write a cookie to the website (it is easier to use a single key value. Here I will only describe how to process the multi-key value under the next cookie)
For simplicity, we use the jquery. Cookie. js plug-in to operate cookies,CodeAs follows:
$. Cookie ('book', 'sn = 081245 & Title = You can't help but know about. net ');
The result is as follows:
2. Use the C # code to implement the same function on the backend. The Code is as follows:
Httpcookie bookcookie = new httpcookie ("book"); bookcookie ["Sn"] = "081245"; bookcookie ["title"] = httputility. urlencode ("you have to know. net "); response. appendcookie (bookcookie );
You must be careful to find that the cookies are actually a little different, that is, "=" is using jquery. cookie. the JS plug-in is also encoded during processing. Such results certainly do not meet our goal.
In fact, this is not hard to understand, jquery. cookie. in JS, you cannot skip 'sn = 081245 & Title =. net' is encoded as a string. Well, let's go to jquery. cookie. modify the code in JS and submit the code to us.
Find the corresponding code
Document. Cookie = [name, '=', encodeuricomponent (value), expires, path, domain, secure]. Join ('');
Change
Document. Cookie = [name, '=', value, expires, path, domain, secure]. Join ('');
In this way, the JS Code above will also be processed accordingly. After modification, it will be:
Function writecookie ()
{$. Cookie ('book', 'sn = 808080' + '& Title =' + encodeuricomponent ('You cannot skip. net '));}
After such processing, we ensure that the cookie values written by the front-end and backend are consistent, which serves as the basis for subsequent reading. In the next article, I will continue to describe that the cookie is read from the front end and the backend is consistent, download the source code.
Notes in this chapter:
1. For non-English and numbers, it must be encoded before writing.
2. The encoding function corresponding to JS and Asp.net is encodeuricomponent.
Source code: Click to download