nguyenminh

Cookie trong JavaScript: Set, Get & Delete

What are Cookies?

A treat is a piece of information that is put away on your PC to be gotten to by your program. You additionally may have delighted in the advantages of treats intentionally or unconsciously. Have you at any point saved your Facebook secret phrase so you don’t need to type it every single time you attempt to login? In the event that indeed, you are utilizing treats. Treats are saved as key/esteem sets.

For what reason do you need a Cookie?

The correspondence between an internet browser and worker happens utilizing a stateless convention named HTTP. Stateless convention treats each solicitation autonomous. Thus, the worker doesn’t keep the information subsequent to sending it to the program. Yet, much of the time, the information will be required once more. Here come treats into an image. With treats, the internet browser won’t need to speak with the worker each time the information is required. All things considered, it very well may be brought straightforwardly from the PC.

Javascript Set Cookie

You can make treats utilizing record. treat property like this.

document.cookie = "cookiename=cookievalue"

Attempt this Example yourself:

<html>
<head>
    <title>Cookie!!!</title>
    <script type="text/javascript">
        function createCookie(cookieName,cookieValue,daysToExpire)
        {
          var date = new Date();
          date.setTime(date.getTime()+(daysToExpire*24*60*60*1000));
          document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
        }
        function accessCookie(cookieName)
        {
          var name = cookieName + "=";
          var allCookieArray = document.cookie.split(';');
          for(var i=0; i<allCookieArray.length; i++)
          {
            var temp = allCookieArray[i].trim();
            if (temp.indexOf(name)==0)
            return temp.substring(name.length,temp.length);
          }
            return "";
        }
       
    </script>
</head>
<body>
  <script>
      var result_check = accessCookie("testdev");
       if (result_check!=""){
         console.log(result_check);
        }
        else
        {
            createCookie("testdev", 'mimh', 1);
        }
  </script>
</body>
</html>

Categorised in: Tổng hợp

0 Comments for "Cookie trong JavaScript: Set, Get & Delete"

Leave a Reply

Your email address will not be published. Required fields are marked *