如何使用按钮onclick从php函数更改会话变量?

时间:2014-02-28 01:54:35

标签: php ajax

所有前端编程都请。

以下是我目前正在处理的实际网站:http://alvincaseria.me/SJA100/ 我有像这样显示的按钮:

  • [1991年之前的故事] [1991年之后] [1991年之前的学生]
  • [1991年批次的故事] [1991] [1991年批次]
  • [1991年以后的故事] [1991年以后] [1991年以后的学生]

我想要实现的是一个php页面,它有一个会话变量来保存年份(例如:1991)。然后,当单击某些按钮时,变量会更改其值。

示例:

  1. 当我点击按钮[1991年之后]时,会话运行一个功能 这是为了增加名为“batch”的会话变量
  2. 当我点击按钮[1991年之前]时,会话运行一个功能 这是假设减少相同的变量。
  3. 目前我正在运行“Onclick = location.href ...”但我想要调用本参考文献中提到的函数()。 How to Call a PHP Function on the Click of a Button

    我是php和ajax的新手,我不知道如何调用上面提到的引用来适应我当前的代码,因为它在我的页面之外。如果可能的话,我可以不用ajax吗?

    这是我的当前代码,您也可以查看我上面提到的当前页面。

      <?php
      session_start();
      // store session data
      $_SESSION['batch']=1991;
      ?>
    
      <html lang="en">
        <head> ... </head>
        <body>
          <?php 
              if($_GET['button1']){add1();}
              if($_GET['button2']){min1();}
    
              function add1()
              {
                $_SESSION['batch']=$_SESSION['batch']+1; 
              }
    
              function min1()
              {
                $_SESSION['batch']=$_SESSION['batch']-1;  
              }
          ?>
    
          ... more codes
    
          // After Year Chosen
          <div class="child"><button type="button" class="btn-styleBT">Short Stories of (Year chosen plus 1)</button></div> 
          <div class="child"><button type="button" class="btn-styleCT" id="btn1" name="btn1" onClick='location.href="?button1=1"'>
                <?php
                //retrieve session data
                echo "after ".$_SESSION['batch'];
                ?>
          </button></div>          
          <div class="child"><button type="button" class="btn-styleBT">Batch of (Year chosen plus 1)</button></div>
    
          ... more codes Middle divs
    
          <div class="child"><button type="button" class="btn-styleBT">Short Stories of (Year chosen minus 1)</button></div>
          <div class="child"><button type="button" class="btn-styleCT" id="btn2" name="btn2" onClick='location.href="?button2=1"'>
                <?php
                //retrieve session data
                echo "before ".$_SESSION['batch'];
                ?>
           </button></div>
           <div class="child"><button type="button" class="btn-styleBT">Batch of (Year chosen minus 1) </button></div>
    
          ... more codes 
    

    有任何想法或建议吗?

1 个答案:

答案 0 :(得分:1)

会话的想法是它们在页面请求中持续存在 - 如果尚未设置变量,则只应在第4行设置变量:

if(!isset($_SESSION['batch']))
    $_SESSION['batch'] = 1991;