我想在不重新加载页面的情况下更改url,因为我使用AJAX函数来重新加载div。问题是,当AJAX加载div时,它不会读取url参数。
我的代码(我已经加载了jquery.js等):
index.php
<a href="#page=1" onClick='refresh()'> Link </a>
<a href="#page=2" onClick='refresh()'> Link2 </a>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
function refresh() {
$("#test").load("mypage.php"); //Refresh
}
</script>
<div id="test">
</div>
mypage.php
<?php
if (isset($_GET['page'])){
$page = $_GET['page'];
}
echo $page;
?>
PHP在不重新加载页面的情况下无法读取片段。这可以使用JS来完成。
下面是我用来读取参数值而不重新加载页面的脚本。我不认为这是最好的方法,因为有一些插件可以用来做同样的事情(还有更多),但它是有效的。我不久前在网上找到了它,但不幸的是,我不记得在哪里:(
var urlParams;
(window.onpopstate = function () {
var match,
pl = /'+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.hash.slice(1);
urlParams = {};
while (match = search.exec(query)) {
urlParams[decode(match[1])] = decode(match[2]);
}
})();
然后,您可以使用获得参数值
urlParams['page']
如果你会大量使用哈希URL,你应该看看这个插件:http://benalman.com/projects/jquery-bbq-plugin/
获取#
哈希标签:
使用PHP(必需的页面加载)
parse_url()你需要的fragment
索引
$url = parse_url($_SERVER['REQUEST_URI']);
$url["fragment"]; //This variable contains the fragment
使用jQuery:(不需要页面加载)
var hash = $(this).attr('href').split('#')[1];
var hash = $(this).attr('href').match(/#(.*$)/)[1];
Demo(不带哈希标签使用)
index.php
<a href="#" class="myLink" data-id="1"> Link </a> | <a href="#" class="myLink" data-id="2"> Link2 </a>
<script type="text/javascript">
$(".myLink").click(function(e) { // when click myLink class
e.preventDefault(); // Do nothing
var pageId = $(this).attr('data-id'); // get page id from setted data-id tag
$.ajax({
type:'POST',
url:'mypage.php', // post to file
data: { id: pageId}, // post data id
success:function(response){
$("#test").html(response); // write into div on success function
}
});
});
</script>
<div id="test"></div>
mypage.php
<?php
// get with $_POST['id']
echo "Loaded Page ID: ".($_POST['id'] ? $_POST['id'] : "FAILED");
?>
您需要向请求的URL传递一个page
参数。
试试这个:
<a href="#page=1" onClick='refresh(1)'> Link </a>
<a href="#page=2" onClick='refresh(2)'> Link2 </a>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
function refresh(pageNumber) {
$("#test").load("mypage.php?page="+pageNumber); //Refresh
}
</script>
您可以通过jQuery中的load()函数传递参数。
有两种常见的方法:
使用get:
JS:
$('#test').load('mypage.php?page=mypage');
PHP:
<?php
if (isset($_GET['page']))
{
$page = $_GET['page'];
}
echo $page;
?>
或者使用数据作为帖子:
JS:
$('#test').load('mypage.php', { page: mypage });
PHP:
if (isset($_POST['page']))
{
$page = $_POST['page'];
}
echo $page;
?>