HTML Get URL参数

时间:2013-07-26 13:30:26

标签: php javascript jquery html ajax

我想更改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;

?>

4 个答案:

答案 0 :(得分:1)

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']

如果你将使用哈希网址工作很多,你应该查看这个插件:http://benalman.com/projects/jquery-bbq-plugin/

答案 1 :(得分:0)

您需要将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>

答案 2 :(得分:0)

获取#哈希标记:

使用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];

演示(使用没有散列标记)

的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");
?>

答案 3 :(得分:0)

您可以通过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;

?>
相关问题