将会话变量传递给javascript

时间:2011-09-09 14:44:43

标签: php javascript session-variables

在ExpressionEngine模板中,我在一个javascript文件中设置一个PHP会话变量,如下所示:(是的,EE将解析PHP并将值插入到javascript中)

<?php session_start(); ?>  
function check_someone_else_result(data) {
  waiting_list_flag = false;
   <?php $_SESSION['waiting_list_flag'] = false;  ?>
  if(data.CanBuy=='YES'){
    show_for_someone_else();
  } else {
    waiting_list_flag = true;
   <?php $_SESSION['waiting_list_flag'] = true;  ?>
    $('#sm_content .oblcontent').html($('#waiting_list').html());
    $('#sm_content a.closebtn').click(function(){location.reload(true);});
    $('#sm_content a.yeswaitbtn').click(function(){show_for_someone_else();});
  } // if(data.CanBuy=='YES')
} // function check_someone_else_result

现在,在show_for_someone_else()函数中,我正在重定向到另一个加载另一个javascript文件的页面,我正在尝试将javascript变量设置为我将会话变量设置为上面的相同值。

<?php session_start(); ?>
   var CART_URL          = '{site_url}store/checkout/cart/';
   $(document).ready(function(){
     // attach the validationEngine to the form
     $("#voucher_form").validationEngine('attach', {
                      scroll: false
     }); // $("#voucher_form").validationEngine

     // handles the NExt button click
     $('#checkout-step-billing a').click(function(){
      $('#checkout-step-billing .voucher_form').submit();
     }); // $('#checkout-step-billing a').click

     // handles keypresses in all the fields in the form to submit the 
     // form when the press enter
     $("#checkout-step-billing .voucher_form input").keypress(function (e) {
      if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        $('#checkout-step-billing .voucher_form').submit();
        return false;
      } else {
        return true;
      }
     }); // $("#checkout-step-billing .voucher_form input").keypress

     // set the wait_list_flag from the session variable
     var wait_list_flag = <?php $_SESSION['waiting_list_flag']; ?>   
   }); // $(document).ready

但我根本没有得到任何东西。

我该如何做?

2 个答案:

答案 0 :(得分:1)

 var wait_list_flag = <?php $_SESSION['waiting_list_flag']; ?>   

应该是

 var wait_list_flag = <?php echo $_SESSION['waiting_list_flag']; ?>;
                            ^^^^                                   ^

如果没有echo,PHP块不会输出任何内容,因此不会将任何内容插入到Javascript块中。你也错过了javascript中的尾随分号,这也可能导致致命的解析错误。

答案 1 :(得分:0)

要设置该值,您需要回显/打印$ _SESSION ['waiting_list_flag'];在第二个片段中。

请记住,在第一个片段中,PHP将首先运行(它不是使用JavaScript运行),因此会话var将始终为true。 (除非你的意思是沃特EE)

相关问题