如何停止使用 onload() 函数以避免在页面刷新时丢失 PHP 输出?

How to stop using onload() function to avoid loosing the PHP output when page refreshed?

我正在使用 onload() 函数来避免在刷新页面时丢失 PHP 输出。我试图避免由 onload 函数引起的震动效果。我还没有找到任何替代方法来做到这一点。如何在不使用 onload 的情况下实现相同的效果?

file.js

function showMe(){
    $.ajax({
         type: "POST",
         url: "output.php",  
         cache: false,       
         data: "action=showMessage",        
         success: function(html){                
            $("#container").html(html);  
          }
   });

return false;
}

index.php

<!DOCTYPE html>
<head>
    <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
    <script type="text/javascript" src="file.js"></script>
</head>
     <body onload="showMe();">
            <div id="container"></div>
            <form id="myForm"></form>
     </body>
</html>

output.php

  if ($action=="showMessage")
  {   
         $query="SELECT * FROM `comm` ORDER BY id ASC";
         $result = mysqli_query($conn,$query);

           if (isset($_REQUEST['parentId'])) { 
                  $parentId = $_REQUEST['parentId']; 
             }
          else { $parentId = 0; }

             $i=0;  $my = array();
         while ($row = mysqli_fetch_row($result)){ 
               $my[$i] = $row; $i++; 
         }
      tree($my, 0, $parentId);
      }

   function tree($Array, $lvl, $ansId, $pid = 0) 
   {   $parentId = $ansId;

      foreach($Array as $item)
      {
         if ($item[1] == $pid) 
         {  ?>            
               <div style="margin-left:<?php echo($lvl*40); ?>px">    
               <p><?php echo($item[3]); ?></p>
               <?php  
                    if ($lvl<=4){ echo '<a href="javascript:" onclick="OneComment('.$item[0].');">Reply</a>'; }
               ?> </div> <?php 
           tree($Array, $lvl+1,$parentId, $item[0]);
         }       
      }
   }
  ?>

一个解决方案是让 JavaScript 代码设置一个 cookie,然后让 PHP 代码呈现 HTML 检查是否设置了该 cookie。

例如,提交表单时(假设它调用了showMe()函数并停止了表单手动提交.submit()), set a cookie with document.cookie:

$('#myForm').submit(function(submitEvent) {
    //Store cookie, which can be accessed via PHP on next page-load
    document.cookie = 'formSubmitted=1';
    showMe();
    return false;//don't submit form
});

然后当 index.php 重新加载时,使用 superglobal variable $_COOKIE:

检查该 cookie
if (isset($_COOKIE['formSubmitted'])  && $_COOKIE['formSubmitted']==1) {
    //output the messsages (in the div with id="container"), using the code from output.php
    //perhaps abstracting that code into a common function that can be used
    //in both places
}

请参阅 this phpfiddle 中的示例。请记住,phpFiddle 只允许在 fiddle 中使用一个 php 脚本,因此必须将 output.php 中的代码移至该 PHP 脚本和 运行 仅当有 POST 数据时(例如来自 AJAX 请求)。否则文件中的代码可以分开保存。