Home > Web Front-end > JS Tutorial > body text

How to set cookie value using AJAX request in JavaScript?

WBOY
Release: 2023-08-24 12:17:02
forward
1714 people have browsed it

如何在 JavaScript 中使用 AJAX 请求设置 cookie 值?

We need to set the cookie via AJAX request, or set the cookie with any AJAX request Send these cookies to the server.

One thing to note here is that every AJAX request is automatically sent to any remote server Sends all of our cookies to this server without us having to do anything. So, with this Things are clear, we just need to set a specific key for our document object using JavaScript, Whenever we make a web call, this cookie is automatically sent to the server where we Calling.

The code to set a cookie is-

const token = 'some 323 very 535 random 5445 value';
document.cookie = `token=${token}`;
Copy after login

If we want a cookie that expires at some time in the future, we can create it using the following code-

const token = 'some 323 very 535 random 5445 value';
const expiry = 'Wed, 4 Feb 2021 12:00:00 UTC';
document.cookie = `token=${token} expires=${expiry}`;
Copy after login

This way, When we make any web request, a "token" cookie will automatically be sent to server.

The above is the detailed content of How to set cookie value using AJAX request in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!