获取整个URL,包括查询字符串和锚点

Ale*_*x S 44 php

有没有办法在包含的页面中获取用于请求当前页面的整个URL,包括锚点(#后面的文本 - 我可能使用了错误的单词)?

即页面foo.php包含在bar.php中.如果我在foo.php中使用你的解决方案,我需要它说bar.php?blarg = a#blahblahblah

Kaz*_*zar 83

不,我不敢,因为哈希(包括#的字符串)永远不会传递给服务器,它只是浏览器的行为属性.但是$_SERVER['REQUEST_URI']变量将包含其余部分.

如果您确实需要知道哈希是什么,则必须使用document.location.hashJavaScript属性,该属性包含哈希的内容(然后您可以将其插入表单中,或者使用ajax请求将其发送到服务器).


Mih*_*att 11

// find out the domain:
$domain = $_SERVER['HTTP_HOST'];
// find out the path to the current file:
$path = $_SERVER['SCRIPT_NAME'];
// find out the QueryString:
$queryString = $_SERVER['QUERY_STRING'];
// put it all together:
$url = "http://" . $domain . $path . "?" . $queryString;
echo $url;

// An alternative way is to use REQUEST_URI instead of both
// SCRIPT_NAME and QUERY_STRING, if you don't need them seperate:
$url = "http://" . $domain . $_SERVER['REQUEST_URI'];
echo $url;
Run Code Online (Sandbox Code Playgroud)


kar*_*m79 5

您不能 - 您必须通过 Javascript 将哈希值写入 cookie,以便在后续请求中将其发送到服务器。


Ale*_*ein 5

您可以使用Javascript onload函数传递完整的URL,包括锚点(#之后的部分),该函数将该URL发送到Ajax端点.