小编典典

通过JavaScript将变量从一个html页面传递到另一页面

javascript

我有两个页面-“页面1”和“页面2”。在第1页上,有一个文本框,其值例如为100,最后是一个按钮。

通过按下按钮,我希望javascript将文本框的值保存在全局(?)变量中,然后跳转到第2页。使用“
window.onload”,我想要第二个Javascript函数来提醒保存在page1的值。

这是我的Javascript代码:

<script type="text/javascript">

var price; //declare outside the function = global variable ?

function save_price(){

    alert("started_1"); //just for information

    price = document.getElementById('the_id_of_the_textbox').value;

    alert(price); //just for information         
}



<script type="text/javascript">

function read_price(){

    alert("started_2");

    alert(price);

}

在“页面1”上,我有一个带有以下内容的发送按钮:

<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>

它启动Javascript函数并将我正确地重定向到我的page2。

但是第二页:

window.onload=read_price();

我总是得到全局可变价格的“未定义”值。

我已经阅读了很多有关这些全局变量的内容。例如在此页面上:全局变量有问题..但是我无法使其正常工作…

为什么这不起作用?


阅读 526

收藏
2020-05-01

共1个答案

小编典典

在不阅读您的代码而仅阅读您的方案的情况下,我将使用解决localStorage。这是一个示例,我将prompt()简短地使用。

在第1页:

window.onload = function() {
   var getInput = prompt("Hey type something here: ");
   localStorage.setItem("storageName",getInput);
}

在第2页:

window.onload = alert(localStorage.getItem("storageName"));

您也可以使用cookie,但是localStorage允许更多空间,并且在您请求页面时不会将它们发送回服务器。

2020-05-01