如何根据URL中提到的元素ID来使页面做两件不同的事情?例如,如果网址是website.com/page#id1,那么页面会做一件事,如果是website.com/page#id2,那么它会做另一件事吗?
答案 0 :(得分:1)
无论是服务器端还是客户端,答案都是肯定的。
服务器端,您的网址需要与您的网站结构不同,例如:
http://website.com/page?id=1
...或使用RESTful路由
http://website.com/page/1
后者可以通过Apache的mod_rewrite
。
要访问PHP代码中的id
值,您需要$_GET['id']
,并对其进行适当处理。
客户端,您需要使用location.hash
或location.href
使用JavaScript执行此操作。 GitHub通过可导航散列实现了这一效果。
答案 1 :(得分:0)
URL的哈希部分未传递给服务器,您需要使用例如。用来做JavaScript的。
在JavaScript中,“哈希”部分的URL可用:
var hash_part = window.location.hash;
并且在获得它之后,您可以例如:
将将哈希传递给服务器的页面重定向,例如。那样:
window.location = '/check_hash.php?hash=' + hash_part.split('#')[1]
或做某事而无需致电服务器:
alert('My hash is "' + hash_part + '", no need to call the server!');
有帮助吗?
答案 2 :(得分:0)
如果您想使用PHP,您可以在URL中提供参数,例如:
website.com/page.php?do=something
或
website.com/page.php?do=somethingelse
因此,您应该使用问号将参数传递给PHP,而不是使用您在问题中使用的#标签。
在PHP代码中,您可以获取此参数并根据其值执行某些操作:
<?php
$param = $_GET['do'];
if ($param == "something") {
//Do something...
}
else if ($param == "somethingelse") {
//Do something else...
}
?>
答案 3 :(得分:0)
服务器端:http://www.php.net/manual/en/language.variables.external.php
在客户端,您必须使用location.hash
或location.href
来确定已将id
发送到您的网页。
答案 4 :(得分:0)
如果你想根据网址参数改变页面加载的内容,你可以像这样阅读
if($_GET["id"] == "test"){
do your stuff
}
答案 5 :(得分:0)
如果客户端那么你将需要使用javascript。例如
<script>
if (location.hash == 'id1') {
alert('page1!');
}
else if (location.hash == 'id2') {
alert('page2!');
}
</script>