简体   繁体   English

会话变量无更新

[英]Session variable no updating

I have two php pages 我有两个PHP页面

page1.php page1.php中

    <?php
    session_start();
     ?
  <script>
  function request(){
  $.ajax({
  cache: false,
  type: "POST",
  url: 'page2.php',
  success: function(data) {
     alert(<?php echo $_SESSION['value'];?>);
  },    
    complete: function() {
   setTimeout(function(){request();}, 2000); 
   }
   });
   };
   </script>

page2.php 使page2.php

    <?php
    session_start();
    $_SESSION['value'] = //Assign a random value.//
    echo $_SESSION['value'];
     ?>

The problem is everytime Ajax is called page2.php echos the current "$_SESSION['value']" value. 问题是每次Ajax被称为page2.php都会回显当前的“ $ _SESSION ['value']”值。 But in page1.php alert shows the old "$_SESSION['value']" value unless i refresh the page, after which it shows current value untill Ajax is been called again and the value gets updated. 但是在page1.php中,除非我刷新页面,否则警报会显示旧的“ $ _SESSION ['value']”值,此后它将显示当前值,直到再次调用Ajax并更新该值为止。 I have no clue as to why this is happening. 我不知道为什么会这样。

Just think for a second: when is your <? ?> 请想一想:您的<? ?> <? ?> executed? <? ?>执行? When your html code with your script is rendered on server side . 当带有脚本的html代码在服务器端呈现 That means, it is a constant unless you refresh your page - when you get another constant. 这意味着,除非您刷新页面-当您获得另一个常量时,它是一个常量。 You should render the value into the response of page2 on the server side - and echo the data you got. 您应该将值呈现到服务器端page2的响应中,并回显您获得的data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM