Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách đặt cookie cho nhiều trang bằng JavaScript

Để cookie có hiệu lực trên toàn site (nhiều trang), set path=/.

Ví dụ

<!DOCTYPE html>
<html>
<head>
    <script>
        function WriteCookie() {
            if (document.myform.customer.value === "") {
                alert("Vui lòng nhập giá trị!");
                return;
            }
            var cookievalue = encodeURIComponent(document.myform.customer.value);
            document.cookie = "name=" + cookievalue + "; path=/";
            document.write("Đã đặt Cookie site-wide: name=" + cookievalue);
        }
    </script>
</head>
<body>
    <form name="myform">
        Nhập tên: <input type="text" name="customer"/>
        <input type="button" value="Đặt Cookie" onclick="WriteCookie()"/>
    </form>
</body>
</html>

Cookie với path=/ sẽ được gửi kèm mọi request đến bất kỳ trang nào trên domain đó.