gpt4 book ai didi

javascript - 记住跨多个页面的 javascript 变量

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

我有一个数据库和2个下拉菜单,使用javascript从所选下拉菜单中获取值,然后将其发送到我的PHP,然后PHP从数据库带回信息并将其显示在表格中,在那里有两个表,因为有 2 个下拉菜单。这是我的 JavaScript:

    function choice1()
{
var x = document.getElementById("select1");
a = x.options[x.selectedIndex].value;
window.location.href = "index.php?a=" + a + "&b=" + b;
}

function choice2()
{
var y = document.getElementById("select2");
b = (y.options[y.selectedIndex].value);
window.location.href = "index.php?a=" + a + "&b=" + b;
}

发生的情况是,它会等待两个下拉菜单发生更改,然后再更改两个表,我希望它做的是在一个表发生更改后立即更改表,但保持另一个表不变。我认为这意味着需要存储 javascript 变量 a 或 b,以便在页面更改时可以调用它,以便 PHP 为第二个表提供相同的信息。

最佳答案

您可以通过多种方式保存数据:

示例是:

cookies:Javascript getCookie functionshttps://developer.mozilla.org/en-US/docs/Web/API/document.cookie

localStorage,获取变量,隐藏输入。

我建议在这种情况下使用 localStorage (html5),因为它非常安全且易于使用。

//    getter function of 'persistent' variables.
function getPersistent(myVar) {
// ensure the localStorage object exists.
// return the variable we are looking for if it does or: undefined.
return (window.localStorage)? localStorage.getItem(myVar) : undefined;
}

// setter function of 'persistent' variables.
function setPersistent(myVar, value) {
// ensure the localStorage object exists.
if (window.localStorage) {
// set the variable.
localStorage.setItem(myVar, value);
}
}

// first run (page refresh) returns undefined.
// second run returns 4.
console.log(getPersistent('test'));

// we set the localStorage var 'test' to '4'.
// note that localStorage only saves strings.
// so you need to parse/convert the data if you want to modify.
console.log(setPersistent('test', '4'));

// returns localStorage var 'test' ==> 4.
console.log(getPersistent('test'));

fiddle :http://jsfiddle.net/kychan/2WJX4/

关于javascript - 记住跨多个页面的 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23591586/

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