2016-11-15 49 views
2

我的主頁通過一個變量的值:得到一個jQuery觸發事件

$(function(){ 
     $('.controls').click(function(){ 
     var id = $(this).attr('id'); //which in this case will be "pets" 
     $.ajax({ 
      type:"POST", 
      data:"page="+id, 
      url:"controller.php", 
      success:function(result){ 
       $('#content').html(result); 
      } 
     }); 
     }); 
    }); 

</script> 

if (isset($_GET['myFave'])){ 
?> 
<script> 

    $(function(){ 
    var animal = "<?php echo $_GET['myFave'];?>"; 
    $('#pets').trigger('click',[{'myFave':animal}]); 
    }); 
</script> 
<?php 
} 
?> 

Controller.php這樣

$page = $_POST['page']; //which will be "pets" 
    require_once($page.".php"); 

pets.php

<table align='center'> 
    ////some data 
    /// how do i access trigger here? 

如果用戶點擊在url上http://server.com?myFave=dog

on m y主頁我需要觸發點擊「寵物」。

所以主頁:

如何將我訪問的pets.php觸發傳遞的則params的價值?

+0

而不是'$ _GET ['myFave']'你可以使用'$ page' – RST

回答

1

您不會將該變量的值發送到controller.php,因此您現在無法訪問該變量。

發送它,你可以這樣做:

主頁:

$(function(){ 
     $('.controls').click(function(event, myFave){ 
              ^^^^^^ get the additional parameters you might send in 
     var id = $(this).attr('id'); //which in this case will be "pets" 
     $.ajax({ 
      type:"POST", 
      // Send all data to the server 
      data: {page: id, myFave: myFave}, 
          ^^^^^^^^^^^^^^ also send this key-value pair 
      url:"controller.php", 
      success:function(result){ 
       $('#content').html(result); 
      } 
     }); 
     }); 
    }); 

</script> 

if (isset($_GET['myFave'])){ 
?> 
<script> 

    $(function(){ 
    var animal = "<?php echo $_GET['myFave'];?>"; 
    $('#pets').trigger('click',[animal]); 
           ^^^^^^^^ Add the extra parameter values 
    }); 
</script> 
<?php 
} 
?> 

然後,你將有機會獲得它在pets.php

$myFave = isset($_POST['myFave']) ? $_POST['myFave'] : null; 

或者,您也可以使用會話以在請求之間保持服務器上的值。