gpt4 book ai didi

javascript - 在javascript中通过URL设置变量

转载 作者:行者123 更新时间:2023-11-28 15:51:41 25 4
gpt4 key购买 nike

嘿,我想知道以下是否可行:

有一个单页网站,例如index.html和一个变量例如 我的变量 = 123;在这个index.html的js脚本中。URL example.com 将显示index.html

现在是否可以共享一个看起来像 example.com/1234 或类似的链接,然后显示正常的 index.html 文件,但它在 js 脚本内将变量 MyVariable 更改为“1234”?

谢谢! :)

最佳答案

首先,您需要将服务器端任何 example.com/* 形式的 URL 重定向到您的 index.html 文件。如何执行此操作取决于您使用的服务器。

对于 Apache,您需要编辑 .htaccess 文件或配置以添加重写规则:

<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !index
RewriteRule (.*) index.html [L]
</ifModule>

来源:http://www.josscrowcroft.com/2012/code/htaccess-for-html5-history-pushstate-url-routing/

然后,在 JavaScript 代码中,您可以通过 window.location 对象访问当前位置 (URL)。您将对 pathname 属性感兴趣,该属性将包含在您的示例中:/1234

要提取值,您必须执行以下操作:

var MyVariable = window.location.pathname.substring(1);

关于javascript - 在javascript中通过URL设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20343350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com