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

36
我有两个页面 - "页面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);

}

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

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

它启动了Javascript函数并将我正确地重定向到我的page2页面。
但是在第二个页面上:
window.onload=read_price(); 

我总是得到全局变量 price 的 "undefined" 值。
我已经阅读了很多关于全局变量的文章。例如在这个页面:问题与全局变量.. 但是我无法让它工作...
为什么这不起作用呢?

2
你误解了 JavaScript 在浏览器中的“全局变量”的含义。它们仍然与设置它们的页面绑定,不会存在于其他页面中。 - CBroe
全局变量仅对页面全局有效。也许可以查看URL参数https://dev59.com/EXNA5IYBdhLWcg3wZ85R? - nha
@CBroe(和nha)谢谢!我不知道它们仍然与页面绑定。我以为它们是“真正”的全局(适用于所有网页)。 - Kronwied
1
可能是在页面加载之间保留变量的重复问题。 - Liam
6个回答

71

不需要阅读您的代码,只看您的情景,我会使用 localStorage 来解决。 这里是一个例子,我会用 prompt() 简短说明。

在页面1中:

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

在第二页:

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

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


2
这是一个好的解决方案,但你没有解释为什么应该使用它。OP不理解JS中的全局变量。 - ColBeseder
@potasmic 谢谢。真的是一个非常棒且易于实现的解决方案。 :) 我需要考虑(就像LiamB所说的)这个解决方案的一些基本安全性吗? - Kronwied
@ColBeseder,Krownied:localStorage是按域名存储的。其他网站无法访问您的localStorage,除非您已经包含了来自其他来源(例如Google Analytics)的其他脚本。sessionStorage在关闭选项卡时过期。Cookies的过期时间比localStorage短。但是,如果数据包含敏感信息,则应该投资于后端交换方案,而不是直接存储到浏览器中,用户可以查看、编辑等(就像cookies一样)。 - potasmic
在我的页面2中,它说localstorage未定义。 - Alberto Martínez
对我来说,它根本没有存储...在第二页中,localStorage.getItem("key")的结果是null - Revolucion for Monica
显示剩余2条评论

9

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

如何使用JavaScript获取查询字符串值

  • 因此,页面1重定向到page2.html?someValue=ABC
  • 然后,页面2可以读取查询字符串,特别是键“someValue”

如果这不仅仅是一个学习练习,您可能需要考虑安全性方面的影响。

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


4
你有几种不同的选择:
  • 你可以使用SPA路由器,例如SammyJS或Angularjs和ui-router,这样你的页面就是有状态的。
  • 使用sessionStorage来存储你的状态。
  • 将值存储在URL哈希上。

@LiamB提出了一个非常好的观点。我的建议和他的建议都存在安全隐患,用户可以通过更改查询字符串参数、哈希参数、本地存储数据或其他方式来更改值。您应该始终在后端服务上对数据进行验证。 - Martin
如何在简单的HTML中使用会话? - Amir

3
为了实现这个功能,我建议在链接数据中发送数据。这是一种不需要使用PHP的非常简单的方法。只需在第二页获取链接并用 "" 替换先前的链接即可。
Page_One.html:
<script>
    //Data to be transfered
    var data = "HelloWorld";

    //Redirect the user
    location.replace("http://example.com/Page_Two.html?" + data);
</script>

第二页.html:

<script>
//Get the current link
var link = window.location.href;

//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");

//Display content
document.write("Page_One.html contains:" + link + "");
</script>

希望这有所帮助!

1

我有一个简单的方法(纯JS):

页面一:

<a href= "www.example.com/mypageTWO.html?gtk=SGVsbG8gV29ybGQh==">Goto Your Info</a>

注意:您需要将GTK值(即参数值)编码为Base64。
接下来是第二页:

    <script>

    // first we get current URL (web page address in browser)
    var dloc= window.location.href;

    //then we split into chunks array
    var dsplt= dloc.split("?");

//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1] 

    var sanitize= dsplt[1].split("=");

    // now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it

    var dlen= sanitize.length;
    var FinString= "";
    // we will start from 1, bcoz first element is GTK the key we don't // want it
    for(i=1;i<dlen;i++)
    {    
    FinString= FinString+sanitize[i];
    }
    // afterwards, all the Base64 value will be ONE value.
    // now we will convert this to Normal Text
    var cleantxt= window.atob(FinString);
    document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";

您可以使用参数解码信息做任何事情...例如,通过由JavaScript自动提交的“POST”方法表单立即将访问者重定向到另一个页面,最终导向到php页面,不带任何可见参数,但具有隐藏的不可见参数。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接