2010-10-02 54 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; 

?>