gpt4 book ai didi

javascript - 将选择器保存在 cookie 中并取回该 cookie

转载 作者:行者123 更新时间:2023-11-28 00:42:15 25 4
gpt4 key购买 nike

我想通过下拉菜单询问我的 web 应用程序中的用户他们想要打开哪个学校网站,然后将其保存在 cookie 中,并在下次打开 web 应用程序时自动打开该网站。我不太擅长 JS,所以请解释一下。

提前致谢。

<head>
<script>
<!-- Cookie script -->
</script>
</head>
<body>
<form>
<select id="class">
<option value="Choose">Choose</option>
<option value="flah">School#1</option> <!-- Should redirect to site #1 -->
<option value="june">School#2</option> <!-- Should redirect to site #2 -->
</select>
<button type="submit">V&auml;lj</button>
</form>
</body>

更新:

<

form>
<select id="class">
<option value="Choose">Choose</option>
<option value="flah">School#1</option> <!-- Should redirect to site #1 -->
<option value="june">School#2</option> <!-- Should redirect to site #2 -->
</select>
<button type="submit" onclick="setCookie()">V&auml;lj</button>
</form>

<script type="text/javascript" language="javascript">
function setCookie(cookiename, cookievalue, cookieexdays) {
var d = new Date();
d.setTime(d.getTime() + (cookieexdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cookiename+ "=" + cookievalue+ "; " + expires;
}

function getCookie(cookiename) {
var name = cookiename+ "=";
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);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}

function checkCookie() {
var school = getCookie("SelectedSchool");
if (school!= "") {
//redirect to user to link
alert("Welcome to the " + school);
} else {
user = prompt("Please choose your name:", "");
if (school != "" && school != null) {
setCookie("SelectedSchool", school, 365);
}
}
}
</script>

最佳答案

要创建 cookie,请使用:

document.cookie="key=value";

要获取选择使用的值(jquery 中的示例):

var val = $("#class").val();

将其保存在 cookie 中。现在,下次用户登录时,使用以下方式读取 cookie:

var x = document.cookie;

并重定向他:

location.href = "link";

祝你好运

关于javascript - 将选择器保存在 cookie 中并取回该 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27799572/

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