gpt4 book ai didi

javascript - Cookie 为空,但在浏览器中有一个值

转载 作者:行者123 更新时间:2023-12-03 10:03:54 26 4
gpt4 key购买 nike

我正在尝试设置一个存储当前 TimezoneOffset 的 cookie。

         window.onload = function () {

var timezone_cookie = "timezoneoffset";

if (!$.cookie(timezone_cookie)) { // if the timezone cookie not exists create one.

// check if the browser supports cookie
var test_cookie = 'test cookie';
$.cookie(test_cookie, true);

if ($.cookie(test_cookie)) { // browser supports cookie

// delete the test cookie.
$.cookie(test_cookie, null);

// create a new cookie
$.cookie(timezone_cookie, new Date().getTimezoneOffset());

location.reload(); // re-load the page
}
}
else { // if the current timezone and the one stored in cookie are different then
// store the new timezone in the cookie and refresh the page.

var storedOffset = parseInt($.cookie(timezone_cookie));
var currentOffset = new Date().getTimezoneOffset();

if (storedOffset !== currentOffset) { // user may have changed the timezone
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
location.reload();
}
}
};

但是当我稍后尝试读取该值时,Visual Studio 中的调试工具告诉我,它是“null”。

如果我加载页面并检查 cookie,则会设置一个值 (-120)。有人可以告诉我我做错了什么吗?

JavaScript 位于 _Layout.cshtml 文件内。我想要使​​用 cookie 执行的代码如下所示:

var timeOffSet = HttpContext.Current.Session["timezoneoffset"];  // read the value from session

if (timeOffSet != null)
{
var offset = int.Parse(timeOffSet.ToString());
dt = dt.AddMinutes(-1 * offset);

return dt.ToString("yyyy-MM-dd HH:mm");
}

// if there is no offset in session return the datetime in server timezone
return dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm");

函数是从View中调用的,所以此时js代码应该已经执行完毕。

最佳答案

我认为您尝试以错误的方式获取该值 - cookie 未存储在 session 变量中。

您可以改用这一行:

HttpCookie cookie = Request.Cookies["timezoneoffset"];
if ((cookie != null) && (cookie.Value != ""))
{
var offset = int.Parse(cookie.Value.ToString());
dt = dt.AddMinutes(-1 * offset);
return dt.ToString("yyyy-MM-dd HH:mm");
}
return dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm");

关于javascript - Cookie 为空,但在浏览器中有一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30453822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com