2010-10-02 49 views
4

如何在php中获得散列值的变量。Php从URL获得散列值

我有这样

catalog.php#album=2song=1 

页面上的变量i怎样才能获得专辑和歌曲的值并把它们放到PHP变量?

+0

[PHP能否读取URL的哈希部分?](http://stackoverflow.com/questions/940905/can-php-read-the-hash-portion-of-the-url) – 2011-12-07 18:00:28

回答

4

只需加入@亚历克的答案。

有一个parse_url()功能:

哪些可以返回fragment - after the hashmark #。然而,在你的情况下,将在hashmark后返回所有值:

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

由于@NullUserException指出,除非你有事先的网址这真的是毫无意义的。但是,尽管如此,我仍然感到很高兴。

+2

除非事先有URL,否则这是无用的。 – NullUserException 2010-10-02 23:35:12

+0

确实。让我把它编辑成我的答案。 – 2010-10-02 23:37:37

+0

谢谢。听起来像我可以将这个想法变成我需要的东西。 – Andelas 2010-10-02 23:42:17

8

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

1

您可以为此使用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; 

?>