javascript Php从URL获取哈希值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3847870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Php to get value of hash from URL
提问by Andelas
How can I get a variable of a hash in php.
如何在 php.ini 中获取散列变量。
I have a variable on page like this
我在页面上有一个像这样的变量
catalog.php#album=2song=1
How can i get the album and song values and put them into PHP variables?
如何获取专辑和歌曲值并将它们放入 PHP 变量中?
回答by Alec
You can't get this value with PHP because PHP processes things server-side, and the hash in the URL is client-side only and never gets sent to the server. JavaScript canget the hash though, using window.location.hash(and optionally call on a PHP script including this information, or add the data to the DOM).
您无法使用 PHP 获取此值,因为 PHP 在服务器端处理事物,并且 URL 中的哈希值仅在客户端使用,永远不会发送到服务器。JavaScript可以获取哈希,使用window.location.hash(和可选地调用包含此信息的 PHP 脚本,或将数据添加到 DOM)。
回答by Russell Dias
Just adding onto @Alec's answer.
只是添加到@Alec 的答案中。
There is a parse_url()function:
有一个parse_url()功能:
Which can return fragment - after the hashmark #. However, in your case it will return allvalues after the hashmark:
哪个可以返回fragment - after the hashmark #。但是,在您的情况下,它将返回哈希标记后的所有值:
Array
(
[path] => catalog.php
[fragment] => album=2song=1
)
As @NullUserException pointed out, unless you have the url beforehand this really is pointless. But, I feel its good to know nonetheless.
正如@NullUserException 指出的那样,除非您事先拥有 url,否则这确实毫无意义。但是,我觉得还是很高兴知道。
回答by aesede
You can use AJAX/PHP for this. You can get the hash with javaScript and load some contents with PHP. Let's suppose we're loading the main content of a page, so our URL with hash is "http://www.example.com/#main":
您可以为此使用 AJAX/PHP。您可以使用 javaScript 获取哈希并使用 PHP 加载一些内容。假设我们正在加载页面的主要内容,因此带有哈希值的 URL 是“ http://www.example.com/#main”:
JavaScript in our head:
我们脑海中的 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);
The PHP could have something like:
PHP 可能有以下内容:
<?php
// very unsafe and silly code
$content_hash_name = $_GET['content'];
if($content_hash_name == 'main'):
echo "Welcome to our Main Page";
endif;
?>

