如何在 html 链接中发送参数以及如何检索它

How to send a parameter in html link and how to retrieve it?

本文关键字:何检索 检索 html 链接 参数      更新时间:2023-09-26

这是我带有href的html标签

<a href='components/home/singleActivity.html?view="search"'>
....
</a>

我想发送一个字符串参数,这是正确的方法吗?

如何在 JavaScript 中检索该参数? 以及如何为同一个 href 发送 2 个参数?

发送两个参数将它们与&连接起来components/home/singleActivity.html?view=search应该没有引号

components/home/singleActivity.html?foo=bar&baz=quux

要在 JavaScript 中读取它们,请使用以下代码:

var params = {};
location.search.slice(1).split("&").forEach(function(pair) {
   pair = pair.split("=");
   params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
});

尝试

<a href='components/home/singleActivity.html?view=Search&test2=New'>
MyLink
</a>

为了在URL中发送参数,您不需要将值括在引号('')或双引号("")。您只需要发送值(或多个值),如下所示。

components/home/singleActivity.html?view=search&secondvalue=anythingthatyouthinkof

还要记住,您需要跟踪 urlencoding。

为了检索参数,这个线程非常详细地解释了它。

要发送多个值,您可以使用?view=search&key2=value2&key3=value3等等。

此外,要访问这些参数,您可以使用 window.location 访问 URL。

类似的东西

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

这将在 URL 中提供 ? 之后的所有内容。