Hướng dẫn thao tác với Cookie trong jQuery

Cookie là khái niệm quen thuộc với các nhà phát triển web. Khi người dùng đăng nhập, việc lưu tên tài khoản vào máy local là phổ biến, nhưng với mật khẩu, bạn nên mã hóa bằng MD5 để bảo vệ thông tin cá nhân. Bài viết này sẽ hướng dẫn cách sử dụng Cookie với jQuery một cách đơn giản và hiệu quả, giúp bạn thao tác dễ dàng hơn trong các dự án.

Các thao tác cơ bản với Cookie trong jQuery:

$.cookie('the_cookie'); // Lấy giá trị cookie
$.cookie('the_cookie', 'the_value'); // Thiết lập cookie
$.cookie('the_cookie', 'the_value', { expires: 7 }); // Thiết lập cookie với thời gian sống 7 ngày
$.cookie('the_cookie', '', { expires: -1 }); // Xóa cookie
$.cookie('the_cookie', null); // Xóa cookie (cách khác)
$.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true}); // Tạo cookie mới với thời gian sống, đường dẫn, tên miền và bảo mật

Nhiều người mới bắt đầu thường gặp lỗi khi thử nghiệm: tạo thư mục, tải file JS, viết code, mở file HTML trực tiếp trên trình duyệt và thấy cookie không được lưu. Nguyên nhân là do cookie hoạt động dựa trên tên miền. Nếu bạn mở file HTML cục bộ (ví dụ: file:///C:/test.html), cookie sẽ không hoạt động. Cookie chỉ có hiệu lực khi được chạy từ một máy chủ (server) hoặc localhost. Vì vậy, hãy triển khai ứng dụng lên Tomcat hoặc server tương tự để kiểm tra.

Dưới đây là ví dụ cụ thể với Java Web:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>Cookie Test</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <script src="jquery-1.10.2.min.js" ></script>
    <script src="jquery.cookie.js" ></script>
  </head>
  
  <body>
    <input type="text" name="name" id="name" /><br/>
    <input type="password" name="password" id="password" /><br/>
    <input type="submit" class="btn" value="Lưu (theo vòng đời trình duyệt)" /> | 
    <input type="submit" class="btn" value="Lấy giá trị" /> | 
    <input type="submit" class="btn" value="Lưu (có thời gian sống)" /> | 
    <input type="submit" class="btn" value="Xóa cách 1" /> | 
    <input type="submit" class="btn" value="Xóa cách 2" /> | 
    <input type="submit" class="btn" value="Tạo cookie có cấu hình đầy đủ"/>

    <script>
        $(".btn").on("click", function() {
            var index = $(this).index();
            if (index === 4) { // Lưu cookie không có thời gian (theo phiên)
                $.cookie("password", $("#password").val());
            } else if (index === 5) { // Lấy cookie
                alert($.cookie("password"));
            } else if (index === 6) { // Lưu cookie với thời gian 7 ngày
                $.cookie("password", $("#password").val(), { expires: 7 });
            } else if (index === 7) { // Xóa cookie cách 1
                $.cookie('password', '', { expires: -1 });
            } else if (index === 8) { // Xóa cookie cách 2
                $.cookie('password', null);
            } else if (index === 9) { // Tạo cookie với đường dẫn, tên miền và bảo mật
                $.cookie('password', $("#password").val(), { expires: 7, path: '/', domain: 'http://localhost:8080/', secure: true });
            }
        });
    </script>
  </body>
</html>

Tải xuống thư viện: jQuery và jQuery Cookie có thể tải tại: jQuery (http://jquery.com/download/) và jQuery Cookie (http://plugins.jquery.com/cookie/).

Thẻ: Cookie jQuery Web Development frontend

Đăng vào ngày 5 tháng 7 lúc 21:22