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

时间:2015-01-04 12:49:12

标签: javascript html variables undefined global

我有两页 - “第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..但我不能让它工作......

为什么这不起作用?

4 个答案:

答案 0 :(得分:35)

如果不阅读您的代码而只阅读您的方案,我会使用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允许更多空格,并且在您请求网页时它们不会被发送回服务器。

答案 1 :(得分:6)

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

how to get query string value using javascript

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

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

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

答案 2 :(得分:1)

您有几种不同的选择:

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

答案 3 :(得分:1)

共有两页: Pageone.html:

<script>
var hello = "hi"
location.replace("http://example.com/PageTwo.html?" + hi + "");
</script>

PageTwo.html:

<script>
var link = window.location.href;
link = link.replace("http://example.com/PageTwo.html?","");
document.write("The variable contained this content:" + link + "");
</script>

希望有帮助!