ホームページ ウェブフロントエンド jsチュートリアル jquery.cookieの使用状況_jqueryの詳細な分析

jquery.cookieの使用状況_jqueryの詳細な分析

May 16, 2016 pm 05:08 PM
cookie jquery

Cookie はサーバーによって生成され、ユーザー エージェント (通常はブラウザ) に送信されます。ブラウザは Cookie のキー/値を特定のディレクトリ内のテキスト ファイルに保存し、次回同じ Web サイトに送信します。この Cookie はサーバーに提供されます (ブラウザが Cookie を有効にするように設定されている場合)。

たとえば、ショッピング Web サイトはユーザーが閲覧した製品リストを保存したり、ポータル Web サイトはユーザーが閲覧したいニュースの種類を記憶したりします。 ユーザーの許可があれば、ユーザーが Web サイトにアクセスするたびにログイン情報を入力する必要がないように、ユーザーのログイン情報を保存することも可能でしょうか?

js/jquery で cookie を処理するにはどうすればよいですか?今日は、軽量の Cookie 管理プラグインである Cookie 操作クラス - jQuery.Cookie.js を共有します。

Cookie のダウンロード アドレス: http://plugins.jquery.com/project/cookie.

特別なお知らせです。今日、Google ブラウザーに特別なエラーが検出されました: メソッド $.cookie がありません。 Firefox ブラウザーのプロンプト: $.cookie は関数ではありません。長時間デバッグした結果、同じページに Jquery プラグインが 2 回または複数回導入されると、このエラーが報告されます。

使用方法:

1. jQuery および jQuery.Cookie.js プラグインを導入します。

コードをコピーします コードは次のとおりです:

<script src="jQuery.1.8.3.js" type="text/javascript"></script> <script src="jquery.cookie.js" type="text/javascript"></script>

2. Cookie をファイルに書き込みます

 var COOKIE_NAME = 'username';  
  if( $.cookie(COOKIE_NAME) ){  
    $("#username").val( $.cookie(COOKIE_NAME) );  
  }  
  $("#check").click(function(){  
    if(this.checked){  
      $.cookie(COOKIE_NAME, $("#username").val() , { path: '/', expires: 10 });  
      //var date = new Date();  
      //date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000)); //三天后的这个时候过期  
      //$.cookie(COOKIE_NAME, $("#username").val(), { path: '/', expires: date });  
    }else{  
      $.cookie(COOKIE_NAME, null, { path: '/' }); //删除cookie  
    }  
  });
ログイン後にコピー
機能。

構文: $.cookie(名前, 値, [オプション])

(1) Cookieの値を読み取る

$.cookie(cookieName) cookieName: 読み取るクッキーの名前。

例: $.cookie("username"); Cookie に保存されているユーザー名の値を読み取ります。

(2) 設定したCookieの値を書き込みます:

$.cookie(cookieName,cookieValue); cookieName: 設定する Cookie の名前、cookieValue は対応する値を表します。

例: $.cookie("username","admin"); username という名前の Cookie に値「admin」を書き込みます。

$.cookie("username",NULL); username

という名前の Cookie を破棄します。

(3) [オプション] パラメータの説明:

有効期限: 制限された日付。整数または日付 (単位: 日) を指定できます。ここも注意が必要です。設定しないとブラウザを閉じるとCookieが無効になってしまいます

パス: Cookie 値が保存されるパス。デフォルトでは、作成されたページのパスと一致します。

domin: Cookie ドメイン名属性。デフォルトは、作成されたページのドメイン名と同じです。ここは、クロスドメインの概念に注意してください。プライマリ ドメイン名とセカンダリ ドメイン名を有効にするには、「.xxx.com」を設定する必要があります。

secure: Cookie 値を送信するときにセキュリティ プロトコルが必要かどうかを示すブール値。

例:

コードをコピーします コードは次のとおりです:
$.cookie("いいね", $(":radio[checked]").val(), {
パス: "/"、有効期限: 7
})


Cookie の設定と読み取りのための完全なページ コード:

&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; 
&lt;head&gt; 
  &lt;title&gt;jQuery学习2&lt;/title&gt; 
  &lt;script src="jQuery.1.8.3.js" type="text/javascript"&gt;&lt;/script&gt; 
  &lt;script src="jquery.cookie.js" type="text/javascript"&gt;&lt;/script&gt; 
  &lt;script type="text/javascript"&gt; 
    $(function () { 
      $("#username").val($.cookie("username")); 
      if ($.cookie("like") == "刘德华") { 
        $(":radio[value='刘德华']").attr("checked", 'checked') 
      } 
      else { 
        $(":radio[value='张学友']").attr("checked", 'checked') 
      } 
      $(":button").click(function () { 
        $.cookie("username", $("#username").val(), { 
          path: "/", expires: 7 
        }) 
        $.cookie("like", $(":radio[checked]").val(), { 
          path: "/", expiress: 7 
        }) 
      }) 
    }) 
  &lt;/script&gt; 
&lt;/head&gt; 
&lt;body&gt; 
  &lt;p&gt;&lt;input type="text" id="username" value="" /&gt;&lt;/p&gt; 
  &lt;p&gt; 
    &lt;input type="radio" name="like" value="刘德华" /&gt;刘德华 
    &lt;input type="radio" name="like" value="张学友" /&gt;张学友 
  &lt;/p&gt; 
  &lt;p&gt;&lt;input type="button" value="保存" /&gt;&lt;/p&gt; 
&lt;/body&gt; 
&lt;/html&gt;
ログイン後にコピー
Cookie は本質的には txt テキストであるため、文字列にのみ保存できます。通常、オブジェクトは Cookie に保存する前にシリアル化する必要があり、取得する場合はオブジェクトを再度取得するために逆シリアル化する必要があります。 。


A lightweight cookie plug-in that can read, write, and delete cookies.

jquery.cookie.js configuration

Include the jQuery library file first, and then include the jquery.cookie.js library file

<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>


How to use

Add a new session cookie:


$.cookie('the_cookie', 'the_value');

Note: When the cookie validity period is not specified, the created cookie will be valid until the user closes the browser by default, so it is called a "session cookie"

Create a cookie and set the validity period to 7 days:


$.cookie('the_cookie', 'the_value', { expires: 7 });

Note: When the cookie validity period is specified, the cookie created is called a "persistent cookie".


Create a cookie and set the valid path to the cookie:

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

Note: By default, only the web page that sets the cookie can read the cookie. If you want a page to read the cookie set by another page, you must set the cookie path.

The cookie path is used to set the top-level directory that can read cookies. Setting this path to the root directory of the website allows all web pages to read each other's cookies (generally do not set this path to prevent conflicts)


Read cookie:

$.cookie('the_cookie');

// cookie exists => 'the_value' $.cookie('not_existing'); // cookie does not exist => null


To delete a cookie, pass null as the cookie value:

$.cookie('the_cookie', null);


Explanation of related parameters

expires: 365

Define the validity time of the cookie. The value can be one (in days from the time the cookie is created) or a Date.

If omitted, the cookie created is a session cookie and will be deleted when the user exits the browser.

path: '/'

Default: Only the webpage that sets the cookie can read the cookie.

Define the valid path of the cookie. By default, the value of this parameter is the path to the web page where the cookie was created (standard browser behavior).

If you want to access this cookie throughout the website, you need to set the effective path like this: path: '/'.

If you want to delete a cookie with a valid path defined, you need to include this path when calling the function: $.cookie('the_cookie', null, { path: '/' });.


domain: 'example.com'

Default value: The domain name owned by the webpage that created the cookie.

secure: true

Default value: false. If true, cookie transmission requires the use of a secure protocol (HTTPS).

raw: true

Default value: false. By default, encoding and decoding are automatically performed when reading and writing cookies (use encodeURIComponent to encode and decodeURIComponent to decode).

To turn off this function, just set raw: true.


$.cookie('the_cookie'); // get cookie $.cookie('the_cookie', 'the_value'); // set cookie $.cookie('the_cookie', 'the_value', { expires: 7 }); / / set cookie with an expiration date seven days in the future $.cookie('the_cookie', '', { expires: -1 }); // delete cookie
$.cookie('the_cookie', null); // delete cookie


$.cookie('the_cookie','the_value', {expires: 7, path: '/', domain:'80tvb.com', secure: true});//Complete calling method

//Or this: $.cookie('the_cookie','the_value');

//Delete Cookie: $.cookie('the_cookie',null);

jQuery plug-in to operate cookies, the approximate usage method is as follows

$.cookie('the_cookie'); //Read Cookie value
$.cookie('the_cookie', 'the_value'); //Set the cookie value
$.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});//Create a new cookie including validity period, path domain name, etc.
$.cookie('the_cookie', 'the_value'); //Create new cookie
$.cookie('the_cookie', null); //Delete a cookie


jquery sets cookie expiration time and checks whether cookies are available

Let cookies expire in x minutes
var date = new date();
date.settime(date.gettime() (x * 60 * 1000));
$.cookie(‘example’, ‘foo’, { expires: date });

$.cookie(‘example’, ‘foo’, { expires: 7});


Check if cookies are available
$(document).ready(function() {var dt = new date();dt.setseconds(dt.getseconds() 60);document.cookie = “cookietest=1; expires=” dt.togmtstring( );var cookiesenabled = document.cookie.indexof(“cookietest=") != -1;if(!cookiesenabled){//Cookies cannot be used……..}});

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットな記事タグ

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

jQueryのリファレンスメソッドを詳しく解説:クイックスタートガイド jQueryのリファレンスメソッドを詳しく解説:クイックスタートガイド Feb 27, 2024 pm 06:45 PM

jQueryのリファレンスメソッドを詳しく解説:クイックスタートガイド

jQueryでPUTリクエストメソッドを使用するにはどうすればよいですか? jQueryでPUTリクエストメソッドを使用するにはどうすればよいですか? Feb 28, 2024 pm 03:12 PM

jQueryでPUTリクエストメソッドを使用するにはどうすればよいですか?

jQueryで要素の高さ属性を削除するにはどうすればよいですか? jQueryで要素の高さ属性を削除するにはどうすればよいですか? Feb 28, 2024 am 08:39 AM

jQueryで要素の高さ属性を削除するにはどうすればよいですか?

jQuery のヒント: ページ上のすべての a タグのテキストをすばやく変更する jQuery のヒント: ページ上のすべての a タグのテキストをすばやく変更する Feb 28, 2024 pm 09:06 PM

jQuery のヒント: ページ上のすべての a タグのテキストをすばやく変更する

jQuery を使用してすべての a タグのテキスト コンテンツを変更する jQuery を使用してすべての a タグのテキスト コンテンツを変更する Feb 28, 2024 pm 05:42 PM

jQuery を使用してすべての a タグのテキスト コンテンツを変更する

jQuery における eq の役割と応用シナリオを理解する jQuery における eq の役割と応用シナリオを理解する Feb 28, 2024 pm 01:15 PM

jQuery における eq の役割と応用シナリオを理解する

QQ ブラウザで Cookie をオフにする方法 QQ ブラウザで Cookie をオフにする方法 Mar 11, 2024 pm 05:31 PM

QQ ブラウザで Cookie をオフにする方法

jQuery 要素に特定の属性があるかどうかを確認するにはどうすればよいですか? jQuery 要素に特定の属性があるかどうかを確認するにはどうすればよいですか? Feb 29, 2024 am 09:03 AM

jQuery 要素に特定の属性があるかどうかを確認するにはどうすればよいですか?

See all articles