在Laravel中的页面刷新上删除jQuery中的cookie

delete cookie in jQuery on page refresh in Laravel

本文关键字:删除 jQuery 中的 cookie 刷新 Laravel      更新时间:2023-09-26

我试图在页面刷新时删除cookie,但无法实现。到目前为止,我已经完成了

//delete the cookie on page refresh
window.onunload = unloadPage;
function unloadPage()
{
    $.removeCookie('count', { path: '/' });
}

此代码位于我的js文件的顶部。我也在stackoverflow 尝试过答案

更新我正在使用laravel,我正在使用此代码设置cookie

$response->withCookie(cookie()->forever('count', $count));
document.cookie = 'count=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';

所以,我不得不这样删除cookie

//delete the cookie on page refresh
    $.ajax({
        url:'remove-cookie',
        method:'post',
        success: function(){
            console.log("cookie deleted");
        }
    });

在我的控制器方法

/**
     * delete the count cookie
     */
    public function destroyCookie(){
        $cookie = Cookie::forget('count');
        $response = new Response($cookie);
        $response->withCookie($cookie);
        return $response;
    }

路线为

Route::post('remove-cookie', 'DonnerController@destroyCookie');

我希望它能帮助到与拉拉威尔合作的人。

您不需要使用unload事件,因为每次刷新时,头中包含的每个脚本都将从上到下执行。

正因为如此,如果你想确保页面真的被刷新了,你所要做的就是在脚本的顶部做一个简单的检查,以验证当前的URL是否与以前相同。

以下是一个示例(未测试):

if (document.referrer == window.location.href) {
    // The page was refreshed.
}

希望这能有所帮助!