繁体   English   中英

通过javascript中的URL设置变量

[英]Set a variable through the URL in javascript

嘿,我想知道以下情况是否可能:

有一个单页网站,例如index.html,一个变量,例如MyVariable = 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);

我建议使用php get,如果您使用的是apache,则可以通过链接传输变量

像index.php?myvariable = 1234这样称呼您的页面

<html>
<body>

your variable is <?php echo $_GET["myvariable"]; ?>


</body>
</html>

http://www.w3schools.com/php/php_forms.asp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM