繁体   English   中英

Php从URL获取哈希值

[英]Php to get value of hash from URL

如何在php中获取哈希变量。

我在页面上有一个变量

catalog.php#album=2song=1

如何获取专辑和歌曲值并将它们放入PHP变量?

你不能用PHP获得这个值,因为PHP处理服务器端的东西,而URL中的散列只是客户端,永远不会被发送到服务器。 JavaScript 可以使用window.location.hash 获取哈希值(并且可选地调用包含此信息的PHP脚本,或者将数据添加到DOM)。

刚加入@Alec的回答。

有一个parse_url()函数:

哪个可以返回fragment - after the hashmark # 但是,在您的情况下,它将返回hashmark之后的所有值:

Array
(
    [path] => catalog.php
    [fragment] => album=2song=1
)

正如@NullUserException指出的那样,除非事先有url,否则这实际上是毫无意义的。 但是,我觉得很高兴知道。

您可以使用AJAX / PHP。 您可以使用javaScript获取哈希并使用PHP加载一些内容。 假设我们正在加载页面的主要内容,因此我们带有哈希的URL是“ http://www.example.com/#main ”:

我们头脑中的JavaScript:

 function getContentByHashName(hash) { // "main"
    // some very simplified AJAX (in this example with jQuery)
    $.ajax({
      url: '/ajax/get_content.php?content='+hash, // "main"
      success: function(content){
        $('div#container').html(content); // will put "Welcome to our Main Page" into the <div> with id="container"
      }
    });
 }

 var hash=parent.location.hash; // #main
 hash=hash.substring(1,hash.length); // take out the #

 getContentByHashName(hash);

PHP可以有类似的东西:

<?php
// very unsafe and silly code

$content_hash_name = $_GET['content'];

if($content_hash_name == 'main'):
  echo "Welcome to our Main Page";
endif;

?>

暂无
暂无

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

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