我用HTML5编写了一个单页应用程序。我使用JQuery和散列导航在页面之间导航。到目前为止,这一切都很好。现在我已经编写了一个非常简单的php脚本,可以从数据库中提取博客条目。当然,我希望用户能够链接这些文章和导航标签等。我该如何实现呢?
我尝试http://example.com/#blog?tag=news,但不知怎的,我的php脚本无法捕获该参数
这样做http://www.example.com?tag=news#blog在我看来,它看起来更好,而且# as @AbraCadaver声明仅由浏览器使用。
<?php echo $_GET['tag']; ?> //would output news
这是一个由#
表示的片段,仅由浏览器使用而不传递给服务器。PHP不会接收$_GET['tag']
,也不会接收#blog
,因为你已经构造了它。
尝试?tag=news#blog
,但PHP仍然无法获得#blog
。
你可以使用var $_GET['tag']
必须使用Java脚本如:
var hash = location.hash;
它将返回哈希值给你
但是您需要使用
发送到服务器端Java脚本
我已经解决了这个问题,想在这里分享一下。
这里的潜在问题是用JQuery加载所有内容。虽然我最初的URI是错误的,但http://example.com/?tag=news#blog也没有解决这个问题。变量从未被发送到PHP的$_GET数组,因为index.html不包含任何PHP,脚本通过JQuery/Ajax加载到div中。
所以这里的解决方案是修改我的JQuery函数:function navigate(theHash)
{
var parsed = theHash;
var tag = '';
if ( theHash.indexOf("/") != -1 ){ /* Check if there is a trailing slash in the string */
parsed = theHash.substr(0, theHash.indexOf("/"));
}
if ( theHash.indexOf(",") != -1 ){ /* Check for Parameters to send to PHP */
parsed = theHash.substr(0, theHash.indexOf(","));
tag = theHash.substr(theHash.indexOf(','), theHash.length);
}
if ( parsed.localeCompare("#!portfolio") == 0 ){
$('#content').load('portfolio.html');
}
else if ( parsed.localeCompare("#!blog") == 0 ){
if ( tag.localeCompare('') != 0 )
{
$("#content").load('blog.html?tag='+tag.substr(1, tag.length));
}
else{
$("#content").load('blog.html');
}
}
else{
$('#content').load('front.html');
}
}
因此,在if语句的blog部分进行了一些更改,以加载附加参数的html页面(其中包含php代码),变量被正确传输到php,我可以通过$_GET读取它。虽然这只是一个初稿,需要对更多参数和更健壮的行为进行改进,但它展示了我是如何解决这个问题的。