gpt4 book ai didi

javascript - 如何使用 localstorage 使用 javascript 登录

转载 作者:行者123 更新时间:2023-11-29 10:41:16 24 4
gpt4 key购买 nike

我用javascript写了一个登录代码

function checkLogin()
{
if(localStorage.login=="true")
{
window.location.href = "index.html";
}
else if(localStorage.login=="false")
{
window.location.href = "login.html";
}
}

其中 localStorage.login="true"& "false"已从服务器动态分配

当我包含这段代码时,页面会循环重定向!!

给我解决方案:

如何在执行后删除/销毁用户定义的函数?

如何在 jquery 中执行用户定义的函数仅一次 ondeviceready

最佳答案

我认为最好的解决方案是仅从您要重定向到登录的页面调用此函数,正如 Emad Melad 所说,在 login.html 页面之外。

如果您想要再次访问 login.php 页面的人在登录后被重定向到 index.php,您可以尝试检测您所在的页面,并创建一个 IF 因此,如果它是登录页面,则不会执行。它会是这样的:

function checkLogin()
{
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1)

if(localStorage.login=="true")
{
window.location.href = "index.html";
}
else if(localStorage.login=="false" && filename != 'login.html')
{
window.location.href = "login.html";
}
}

* The snippet code to get the actual URL

但是,根据我在您的代码中读到的内容,您将从调用此函数的每个页面重定向到 index.html

通常,我在我的应用程序中所做的是只检查它是否未登录,如果是这样则重定向到 login.html。我会做的,稍微修改一下你的功能,是:

    function checkLogin()
{
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1)

if(localStorage.login=="true" && filename == 'login.html')
{
window.location.href = "index.html";
}
else if(localStorage.login=="false" && filename != 'login.html')
{
window.location.href = "login.html";
}
}

这样,如果您已登录并且在 login.php 中,您只会被重定向到 index.html,否则您只会被重定向到 login。 html,如果你没有登录,除了 login.html

希望对您有所帮助!

关于javascript - 如何使用 localstorage 使用 javascript 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28624211/

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