在前端使用JavaScript(JS)操作Cookie,而在后端使用Laravel框架处理Cookie,是常见的Web开发任务。Cookie是一种存储在用户浏览器上的小型数据片段,用于跟踪用户状态或存储会话信息。
假设我们有一个名为userPreferences
的Cookie,其值为"darkMode:on"
,我们想添加一个新的偏好设置"notifications:on"
。
function addCookieValue(cookieName, newValue) {
var cookieValue = getCookie(cookieName);
if (cookieValue) {
cookieValue += "," + newValue;
} else {
cookieValue = newValue;
}
setCookie(cookieName, cookieValue, 365);
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
addCookieValue('userPreferences', 'notifications:on');
在Laravel中,我们可以使用response()
辅助函数来设置和修改Cookie。
use Illuminate\Support\Facades\Cookie;
public function updateCookie(Request $request)
{
$cookieName = 'userPreferences';
$newValue = 'notifications:on';
$cookieValue = $request->cookie($cookieName);
if ($cookieValue) {
$cookieValue .= "," . $newValue;
} else {
$cookieValue = $newValue;
}
return response()->withCookie(cookie($cookieName, $cookieValue, 365));
}
Access-Control-Allow-Credentials
头为true
。HttpOnly
和Secure
标志。通过上述方法,你可以使用JS和Laravel向现有Cookie值添加新的值,并确保其安全性和一致性。
领取专属 10元无门槛券
手把手带您无忧上云