Home  >  Article  >  Web Front-end  >  Tips and practices for setting cookies in web development

Tips and practices for setting cookies in web development

WBOY
WBOYOriginal
2024-01-19 08:11:05997browse

Tips and practices for setting cookies in web development

Techniques and practices for setting Cookies in web development require specific code examples

With the rapid development of the Internet, web development is becoming more and more important, and Cookies are A technology that implements state management has also become an indispensable part. In this article, we will introduce how to set cookies in web development, including the concept of cookies, methods of setting cookies, cookie attributes, etc., and provide specific code examples.

  1. The concept of Cookie

A cookie is a small piece of data sent by the web server to the web browser and stored on the user's computer. When a user visits the same web server, the browser sends this cookie back to the server so that the server can identify the user. Cookies are usually used to implement functions such as user login management and shopping cart management.

  1. How to set Cookie

In web development, there are many ways to set Cookie, the most common method is to use JavaScript code. Two common methods of setting cookies are introduced below:

(1) Using the document.cookie attribute

In JavaScript, the document.cookie attribute can be used to set and read cookies. For example:

document.cookie="username=John Doe";

This code will set a cookie named "username" on the user's computer with a value of "John Doe".

If you want to set multiple cookies, you can separate them with semicolons (;), as shown below:

document.cookie="username=John Doe; email=johndoe@example.com";

Among them, the value of "username" is "John Doe", "email" The value is "johndoe@example.com".

(2) Use jQuery plug-in

In addition to using native JavaScript code to set cookies, you can also use jQuery plug-ins to achieve this. For example, use the jquery.cookie.js plug-in to facilitate cookie operations. The code example is as follows:

$.cookie("username", "John Doe");

The above code will set a cookie named "username" on the user's computer with a value of "John Doe".

For Cookies with multiple attributes, you can use a JavaScript object to represent these attributes, as shown below:

var userInfo = {
    "username": "John Doe",
    "email": "johndoe@example.com"
};
$.cookie("userInfo", JSON.stringify(userInfo));

Among them, JSON.stringify is used to convert the JavaScript object into a JSON string. When reading cookies, you can use the JSON.parse method to convert the JSON string into a JavaScript object.

  1. Cookie attributes

In web development, Cookie has several important attributes, including Cookie name, value, expiration time, path, domain, etc.

(1) Cookie name and value

When setting a cookie, you need to specify the cookie name and value. For example:

document.cookie="username=John Doe";

Among them, "username" is the name of the cookie, and "John Doe" is the value of the cookie.

(2) Cookie expiration time

Setting the cookie expiration time can control the storage time of cookies. In JavaScript, you can use the Date object to set the expiration time. For example:

var now = new Date();
var time = now.getTime() + 3600 * 1000;
now.setTime(time);
document.cookie = "username=John Doe; expires=" + now.toGMTString();

This code will set a cookie with an expiration time of one hour.

(3) Cookie path

Setting the cookie path can limit the access range of cookies. For example:

document.cookie="username=John Doe; path=/";

This code will set a cookie with the path to the root directory.

(4) Cookie domain name

Setting the cookie domain name can limit the cookie's access domain. For example:

document.cookie="username=John Doe; domain=example.com";

This code will set a cookie with the domain name "example.com".

  1. Example code

In order to better understand how to set cookies in web development, a complete example code is provided below. The code uses the jQuery plugin to set and read cookies, and sets a cookie that expires in one hour. The sample code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Set Cookie Demo</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>
<body>
    <script>
        $(function(){
            //设置Cookie
            var now = new Date();
            var time = now.getTime() + 3600 * 1000;
            now.setTime(time);
            var userInfo = {
                "username": "John Doe",
                "email": "johndoe@example.com"
            };
            $.cookie("userInfo", JSON.stringify(userInfo), {expires: now});

            //读取Cookie
            var userInfoStr = $.cookie("userInfo");
            var userInfoObj = JSON.parse(userInfoStr);
            console.log(userInfoObj);
        });
    </script>
</body>
</html>

In the above code, we first introduced jQuery and jquery.cookie.js plug-ins, and then used jQuery's $(function(){...} after the page is loaded. ) syntax to execute code. In the code, we use the $.cookie method to set and read cookies, and use the JSON.stringify and JSON.parse methods to convert JavaScript objects and JSON strings.

Summary

This article introduces the skills and practices of setting cookies in web development, including the concept of cookies, methods of setting cookies, cookie attributes, etc., and provides specific code examples. I hope readers can better understand how to use cookies in web development through this article.

The above is the detailed content of Tips and practices for setting cookies in web development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn