Javascript
 Computer >> コンピューター >  >> プログラミング >> Javascript

JavaScriptでCookieから値を作成して読み取るにはどうすればよいですか?


クッキーを作成する

Cookieを作成する最も簡単な方法は、次のような文字列値をdocument.cookieオブジェクトに割り当てることです-

document.cookie = "key1=value1;key2=value2;expires=date";
ここで「expires」属性はオプションです。この属性に有効な日付または時刻を指定すると、Cookieは指定された日付または時刻に期限切れになり、それ以降はCookieの値にアクセスできなくなります。

次のことを試してください。入力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;
               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>
クッキーを読む

document.cookieオブジェクトの値はcookieであるため、cookieの読み取りは書き込みと同じくらい簡単です。したがって、Cookieにアクセスするときはいつでも、この文字列を使用できます。 document.cookie文字列は、名前=値のペアのリストをセミコロンで区切って保持します。ここで、nameはCookieの名前であり、valueはその文字列値です。

次のコードを実行してCookieを読み取ることができます

ライブデモ

<html>
   <head>
      <script>
         <!--
            function ReadCookie() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );

               // Get all the cookies pairs in an array
               cookiearray = allcookies.split(';');

               // Now take key value pair out of this array
               for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split('=')[0];
                  value = cookiearray[i].split('=')[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         //-->
      </script>
   </head>
   <body>
      <form name="myform" action="">
         <p> click the following button and see the result:</p>
         <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
      </form>
   </body>
</html>

  1. CSSとJavaScriptでタブを作成するにはどうすればよいですか?

    CSSとJavaScriptを使用してタブを作成するためのコードは、次のとおりです- 例 <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style>> .tab {    overflow: hidden;    border: 2px solid gray;    backgr

  2. JavaScriptを使用してCookieを読み取る方法は?

    以下は、JavaScriptを使用してCookieを読み取るためのコードです- 注 −この例を実行するには、ローカルサーバーが必要です。 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Documen