我有两个 HTML 页面,example1.html
和 example2.html
。
如何使用查询字符串将变量从 example1.html
传递到 example2.html
,并在 example2.html
中检索该变量不使用任何服务器端代码?
最佳答案
在 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 中。
编辑:忘记了“new Querystring()”的“new”部分。糟糕...
关于javascript - 如何在两个 HTML 页面之间交换变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3724106/