开发者

how to post and get php vars with jquery?

i have a few php vars:

$test = 12345;
$test1 = "test1";
$test2 = "test2";

and i have a jquery function:

onlike:function(response){
    $('input#helpdiv').trigger('click');    
}

what i want is to pass those php vars through a jquery post to another test.php file.

I was thinking on something like this:

var test = <?php echo $test; ?>; 
var test1 = <?php echo $test1; ?>; 
var test2 = <?php ech开发者_如何学Co $test2; ?>; 

onlike:function(response){
    $('input#helpdiv').trigger('click');
    $.post("test.php", { test, test1, test2 } );
}

and then how do i get them in the test.php? just like $_GET["test"], ...

any ideas on how to put this together?

thanks


<script language='javascript'> 
 var test = "<?php echo $test; ?>"; 
  var test1 = "<?php echo $test1; ?>"; 
  var test2 = "<?php echo $test2; ?>"; 

  onlike:function(response){
      $('input#helpdiv').trigger('click');
      $.post("test.php", { test:test, test1:test1, test2:test2  } );
        }
 </script>

in test.php you can access them as $_POST['test'],$_POST['test1'],$_POST['test2']

EDIT:

to avoid problems caused by quotes in between the variable values, as explained in: how to post and get php vars with jquery?

  var test = "<?php echo json_encode($test); ?>"; 

and the values may be accesed in test.php as

 $test1 = json_decode($_POST['test'])


var test = '<?php echo $test; ?>';

You need to put quotes around a value in JS

Also do you have those variables available when page loads ? As javascript will be rendered on page load it will take existing values at that time.

Also check http://api.jquery.com/jQuery.post/ for making call more clearner to handle response.


Just to conclude the comments I made above: 1st quote the string literal vars e.g.

    $test = "test";
var test = '<?php echo $test; ?>';

Then add them as key value pairs to the object you're passing to the post function e.g.

{ test: test }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜