我有一个PHP foreach循环,它正在获取数据数组。一个特殊的数组是href。在我的echo语句中,我像这样将特定的href附加到下一页:
echo '<a href="nextpage.php?url='.stats.'">Stats</a>'
它重定向到我的下一个页面,我可以通过$_GET得到URL。问题是我想要得到附加URL中#后面的值。例如,下一页上的URL看起来像这样:
stats.php?url=basket-planet.com/ru/results/ukraine/?date=2013-03-17#game-2919
我想做的是能够得到#game-2919在javascript或jQuery的第一页,将其附加到URL,并前往stats.php页面。这可能吗?我知道我无法在PHP中获得#后的值,因为它不是发送到服务器端。有解决这个问题的方法吗?
我是这么想的:
echo '<a href="#" onclick="stats('.$stats.');">Stats</a>';
<script type="text/javascript">
function stats(url){
var hash = window.location.hash.replace("#", "");
alert (hash);
}
但这不起作用,我没有得到警报,所以我甚至不能尝试AJAX和重定向到下一页。提前谢谢。
更新:这是我的整个index.php页面。
<?php
include_once ('simple_html_dom.php');
$html = file_get_html('http://basket-planet.com/ru/');
foreach ($html->find('div[class=games] div[class=games-1] div[class=game]') as $games){
$stats = $games->children(5)->href;
echo '<table?
<tr><td>
<a href="stats.php?url=http://www.basket-planet.com'.$stats.'">Stats</a>
</td></tr>
</table>';
}
?>
我的stats.php页面:
<?php include_once ('simple_html_dom.php');
$url = $_GET['url'];
//$hash = $_GET['hash'];
$html = file_get_html(''.$url.'');
$stats = $html->find('div[class=fullStats]', 3);
//$stats = $html->find('div[class='.$hash.']');
echo $stats;
?>
我想要能够做的是将哈希值添加到传递给stats.php的URL。没有太多代码,因为我使用的是简单的HTML DOM解析器。我希望能够使用从stats。php URL的哈希值来查看通过的URL。
在PHP中生成href时使用urlencode,这样当用户单击链接时,哈希部分不会被浏览器丢弃:
index . php:
<?php
include_once ('simple_html_dom.php');
$html = file_get_html('http://basket-planet.com/ru/');
echo '<table>';
foreach ($html->find('div[class=games] div[class=games-1] div[class=game]') as $games){
$stats = $games->children(5)->href;
echo '<tr><td>
<a href="stats.php?url=http://www.basket-planet.com'.urlencode($stats).'">Stats</a>
</td></tr>';
}
echo '</table>';
?>
然后在第二页,解析url的哈希部分
stats.php:
<?php
include_once ('simple_html_dom.php');
$url = $_GET['url'];
$parsed_url = parse_url($url);
$hash = $parsed_url['fragment'];
$html = file_get_html(''.$url.'');
//$stats = $html->find('div[class=fullStats]', 3);
$stats = $html->find('div[class='.$hash.']');
echo $stats;
?>
这是你要找的吗?
function stats(url)
{
window.location.hash = url.substring(url.indexOf("#") + 1)
document.location.href = window.location
}
如果您当前的URL是index.php#test
,而您调用stats('test.php#index')
,它将重定向到index.php#index
。
或者如果你想将当前URL的哈希值添加到自定义URL:
function stats(url)
{
document.location.href = url + window.location.hash
}
如果您当前的URL是index.php#test
,并且您调用stats('stats.php')
,它将重定向到stats.php#test
。
对你的评论:
function stats(url)
{
var parts = url.split('#')
return parts[0] + (-1 === parts[0].indexOf('?') ? '?' : '&') + 'hash=' + parts[1]
}
// stats.php?hash=test
alert(stats('stats.php#test'))
// stats.php?example&hash=test
alert(stats('stats.php?example#test'))