Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm cách nào để tạo cookie dựa trên tên miền bằng JavaScript?


Để tạo cookie dựa trên miền, hãy đặt thuộc tính miền và đường dẫn trên cookie của bạn, chẳng hạn như -

domain=.example.com

Ví dụ

Bạn có thể thử chạy mã sau để tìm hiểu cách tạo cookie dựa trên miền -

Bản trình diễn trực tiếp

<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ){
                  alert("Enter some value!");
                  return;
               }
               cookievalue= escape(document.myform.customer.value) + ";";
               document.cookie = "name=" + cookievalue + ";
               domain=.example.com;path=/";
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>
   </head>
   <body>
      <form name = "myform" action = "">
         Enter name: <input type="text" name="customer"/>
         <input type="button" value="Set Cookie" onclick="WriteCookie();"/>
      </form>
   </body>
</html>