假设有如下URL:
www.example.com/?val=1#part2
PHP可以通过GET数组读取请求变量val1
。
哈希值part2
是否也可读取?还是这只限于浏览器和JavaScript?
假设有如下URL:
www.example.com/?val=1#part2
PHP可以通过GET数组读取请求变量val1
。
哈希值part2
是否也可读取?还是这只限于浏览器和JavaScript?
主要问题是浏览器甚至不会发送一个带有片段标识符的请求。片段标识符将在浏览器中解析,因此可以通过JavaScript访问。
无论如何,你可以使用parse_url()函数将URL解析成各个部分,包括片段标识符,但显然这并不是你所需要的情况。
简单测试,访问http://localhost:8000/hello?foo=bar#this-is-not-sent-to-server
python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"
Serving HTTP on 0.0.0.0 port 8000 ...
localhost - - [02/Jun/2009 12:48:47] code 404, message File not found
localhost - - [02/Jun/2009 12:48:47] "GET /hello?foo=bar HTTP/1.1" 404 -
服务器收到的请求没有 # 符号后面的部分 - 井号后的内容仅在客户端进行锚点查找。<script>alert(window.location.hash);</script>
在PHP中,parse_url()函数可以处理包含片段的URL字符串(http://codepad.org/BDqjtXix):
<?
echo parse_url("http://foo?bar#fizzbuzz",PHP_URL_FRAGMENT);
?>
Output: fizzbuzz
但我认为PHP不会收到片段信息,因为它只是客户端。
它可以通过Javascript获取 - 如window.location.hash
。从那里,您可以将其发送到服务器,例如使用Ajax,或对其进行编码并将其放入URL中,然后可以通过传递到服务器端。
哈希值从不发送到服务器,因此不行。
关于:
动态获取#哈希标记
<script>
var urlhash = window.location.hash, //get the hash from url
txthash = urlhash.replace("#", ""); //remove the #
//alert(txthash);
</script>
<?php
$hash = "<script>document.writeln(txthash);</script>";
echo $hash;
?>
<script>
var urlhash = window.location.hash, //get the hash from url
txthash = urlhash.replace("#", ""); //remove the #
function changehash(a,b){
window.location.hash = b; //add hash to url
//alert(b); //alert to test
location.reload(); //reload page to show the current hash
}
</script>
<?php $hash = "<script>document.writeln(txthash);</script>";?>
<a onclick="changehash(this,'#hash1')" style="text-decoration: underline;cursor: pointer;" >Change to #hash1</a><br/>
<a onclick="changehash(this,'#hash2')" style="text-decoration: underline;cursor: pointer;">Change to #hash2</a><br/>
<?php echo "This is the current hash: " . $hash; ?>
URI中#
后面的部分被称为“片段”,根据定义,它仅在客户端可用/处理(请参见https://en.wikipedia.org/wiki/Fragment_identifier)。
在客户端上,可以使用JavaScript访问它,方法是 window.location.hash
。
<?php
$url=parse_url("http://domain.com/site/gallery/1?user=12#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
?>
这应该可以工作
www.example.com/?val=1#part2
您必须这样做:www.example.com/?redirectUrl=%2F%3Fval%3D1%23part2
当然,在其他页面中,您还必须加入支持重定向到该URL的功能。 当然并非所有用例都适用,但对于书签而言可以工作。请注意,如果您这样做,则不应允许重定向到绝对URL,只能使用相对URL,以确保不会开放自己的不安全重定向。 - Brad Parks