2016-11-15 93 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; 

或者,您也可以使用会话以在请求之间保持服务器上的值。