小编典典

如何在两个HTML页面之间交换变量?

html

我有两个HTML页面,example1.htmlexample2.html

我如何将变量从传递example1.htmlexample2.html使用查询字符串,并在example2.html不使用任何服务器端代码的情况下检索该变量?


阅读 593

收藏
2020-05-10

共1个答案

小编典典

在example1.html中:

<a href='example2.html?myVar1=42'>a link</a>
<a href='example2.html?myVar1=43'>another link</a>

或根据需要使用Javascript生成链接。只要确保?varName = value以某种方式到达example2.html的末尾即可。

然后,在example2.html中,使用Javascript解析example2随附的查询字符串。

为此,您可以尝试使用Querystring。

// Adapted from examples on the Querystring homepage.
var qs = new Querystring();
var v1 = qs.get("myVar1");

另外,parent.document.URL包含您所在页面的完整URI。您可以提取出:

parent.document.URL.substring(parent.document.URL.indexOf('?'), parent.document.URL.length);

并手动对其进行解析,以将您编码的变量提取到URI中。

编辑:忘记了“新Querystring()”的“新”部分。糟糕…

2020-05-10