如何从URL获取“foo”:http://www.loremipsum.com/mysite.html#foo

时间:2014-01-30 12:40:35

标签: javascript php jquery

有没有办法在javascript(jQuery)或PHP中获取.html后的内容?

我尝试过使用PHP $_SERVER['request_uri']和JS window.location.pathname;

但似乎在.html

之后一切都被剥夺了

任何人都知道如何在#foo之后提交.html

6 个答案:

答案 0 :(得分:3)

在Javascript中,您可以使用hash属性获取它:

window.location.hash

答案 1 :(得分:3)

对于javascript试试这个

hash = window.location.hash.substring(1);

但要注意这在IE 7中不起作用。

如果您想支持IE 7

hash = window.location.href.substr(location.href.indexOf("#"));

答案 2 :(得分:0)

你能试试吗,

在Javascript中:

var query = location.href.split('#');
console.log(query[1]);

在PHP中,如果您提供了上述完整网址,则可以使用parse_url(),因为您添加了php标记

$url="http://www.loremipsum.com/mysite.html#foo";
$urls = parse_url($url);        
$fragment = $urls['fragment'];

答案 3 :(得分:0)

无论你是需要在客户端[js]还是在服务器[php]中,它都会完全不同。

在客户端中,您只需通过window.location.hash访问它。

在服务器中,请注意片段永远不会通过HTTP发送,因此您必须将其作为查询字符串发送,或者在请求正文中发送[如果HTTP方法允许]。

答案 4 :(得分:0)

使用window.location.hash而不是window.location.pathname。

答案 5 :(得分:0)

这可能会对您有所帮助:

<?php  
$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";

if ($_SERVER["SERVER_PORT"] != "80"){
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    $urls = parse_url($pageURL);        
    $fragment = $urls['fragment'];
    echo $fragment; //foo
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    $urls = parse_url($pageURL);        
    $fragment = $urls['fragment'];
    echo $fragment; //foo
}
?>