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

问题描述 投票:14回答:3

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

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

这是我的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(); 

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

我已经阅读了很多关于那些全局变量的内容。例如。在这个页面:Problem with global variable..但我不能让它工作......

为什么这不起作用?

javascript html variables undefined global
3个回答
34
投票

如果不阅读您的代码而只阅读您的场景,我会通过使用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允许更多空间,并且在您请求页面时不会将它们发送回服务器。


6
投票

这里最好的选择是使用查询字符串来“发送”该值。

how to get query string value using javascript

  • 所以第1页重定向到page2.html?someValue = ABC
  • 然后,第2页可以读取查询字符串,特别是键'someValue'

如果这不仅仅是一个学习练习,你可能想要考虑这个的安全含义。

全局变量在这里不会帮助你,因为一旦页面被重新加载它们就会被销毁。


1
投票

您有几个不同的选择:

  • 你可以使用像SammyJS,Angularjs和ui-router这样的SPA路由器,这样你的页面就是有状态的。
  • 使用sessionStorage存储您的状态。
  • 将值存储在URL哈希中。
© www.soinside.com 2019 - 2024. All rights reserved.