dsdioa9545 2018-09-25 12:52
浏览 47
已采纳

即使用户点击“返回”,也将PHP变量传递给javascript

Let's start with a typical PHP/html/JavaScript environment. Skipping past the <head> and <body> suppose we have:

<script>
    var foo = <?php echo generateFoo(); ?>;
</script>

Let's suppose this is working perfectly in every way, except for one minor flaw. That is, whenever I navigate away from the page and click "back", I get the old value of foo rather than an updated one.

I understand this error. Clicking "back" loads the page from the cache, not the server, so it returns to the previous value of PHP, not the current one. However, I want it to force update. (This is especially important because the user could be changing the value on another page, and someone who isn't an expert in html would expect "back" to take you to an updated version of the previous page. Code is always easier to change than user behaviour.)

What can I write that will function exactly like the code above, but will also execute when the user navigates back?

(I think the correct solution may use AJAX, but maybe I'm wrong. The page already uses AJAX from a jquery CDN, so I may as well make use of it if I can.)

Edit:

A solution that allows caching but just updates that one variable would be ideal. However if stopping caching is the only solution, I don't even know how to do that. So telling me how to do that would be good.

Copied directly from my code without alteration:

<?php

...

    header("Cache-Control: no-cache, no-store, must-revalidate");
    header("Pragma: no-cache");
    header("Expires: 0 ");
?>

So yes, I have already tried to stop caching. It isn't working in the BFCache.

  • 写回答

1条回答 默认 最新

  • douchunjing6587 2018-09-25 13:29
    关注

    Check out this thread and the code example:

    window.addEventListener("pageshow", function (event) {
      var historyTraversal = event.persisted || 
                             (typeof window.performance != "undefined" && 
                                  window.performance.navigation.type === 2);
      if (historyTraversal) {
        // Reload the page.
        window.location.reload();
      }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗