如何使用 javascript 从第二页到第一页进行通信?

How to communicate from secornd page to first page usin javascript?

我有一个要求,我必须在应用程序的第一页到第二页显示所选的下拉选项。

我试过写FirstPage.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First page</title>
</head>
<body>
<div class="abc">
Dropdown:  <select id="ddlViewBy" onchange="fun()">
<option value="1">select</option>
<option value="2">test1</option>
<option value="3">test2</option>
<option value="4">test3</option>
</select>
<p>selected option is :<b id="abc"></b></p>
<button onclick="redirect()">Redirect</button>
</div>
<script>
function fun(){
    var e = document.getElementById("ddlViewBy");
    var strUser = e.options[e.selectedIndex].text;
    document.getElementById("abc").innerHTML=strUser;
}
function redirect(){
    var linkToSeconPage="http://localhost:63342/test/SecondPage.html";
    window.location.href=linkToSeconPage;
}
</script>
</body>
</html>

和我需要访问 strUser

的 SecondPage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>second page</title>
</head>
<body>
<div>here i want to access the selected dropdown value from first page</div>
</body>
</html>

能否请您介绍一下将 strUser 用于 SecondPage.html 的方法。

还有 window.location.href=linkToSeconPage;在 Firefox 中不起作用。 我也试过 window.location=linkToSeconPage; , window.location.assign(linkToSeconPage);并使用 return false;在此之后在 google 上搜索答案但在 firefox 中没有任何效果,但在 IE 11 上一切正常。

您是否也可以建议在 firefox 中使用的替代方案。 提前致谢。

使用 get 参数将值传递到第二页,例如

 window.location.href=linkToSeconPage + '?val=valueToPassThrough';

然后在第二页使用:

var theValue = window.location.href.split('?')[1].split('=')[1];

但是请注意,这不会考虑传递给页面的其他 get 参数,在这方面它很脆弱。

这是一种非常手动的方式,您可能想编写一个函数来为您提取这种确切的行为 - 当然还要检查 split 的问题 - 上面的代码假设有URL 中的 ? 并且所需的参数是第一个。

location.assign(url)location = url 在 FireFox 中是 equivalent and supported。尝试离开 window.

按照@Sam 的建议将值附加到查询字符串是一个不错的选择。另一个选项在更复杂的情况下很有用——或者当您不想在查询字符串中公开所选值(该值将存储在记录的文件中)时,使用 SessionStorage。在第一页,添加

sessionStorage.setItem('SELECTED', strUser);

并且在页面上,您可以使用

检索
sessionStorage.getItem('SELECTED');

SessionStorage 在用户当前会话的生命周期内将值存储在浏览器中。 token/key(在我的示例中为 SELECTED,但可以是任何文本)的范围为域;因此其他网站无法读取您放入 SessionStorage 的数据。