获取jquery触发器事件中传递的变量的值


get the value of a variable passed in a jquery trigger event

我的主页:

  $(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

在我的主页上,我需要触发点击"宠物"。

在主页面:

我如何访问在pets.php上的触发器中传递的参数值?

您没有将该变量的值发送给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;

或者,您可以使用会话在请求之间将该值保留在服务器上。