如何使用 JavaScript 建立基於域的 Cookie?


要建立基於域的 Cookie,請在 Cookie 中設定域和路徑屬性,如下所示 -

domain=.example.com

示例

你可以嘗試執行以下程式碼來學習如何建立基於域的 Cookie -

即時演示

<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>

更新於: 16-Jun-2020

238 瀏覽量

開啟您的 職業

完成課程可獲得認證

開始學習
廣告