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

时间:2017-05-30 15:53:44

标签: javascript php jquery ajax onload

我使用onload()函数来避免在刷新页面时丢失PHP输出。我试图避免上传功能引起的震动效应。我还没有找到任何替代方法来做到这一点。如何在不使用 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]);
         }       
      }
   }
  ?>

1 个答案:

答案 0 :(得分:0)

一种解决方案是让JavaScript代码设置一个cookie,然后使用PHP代码来检查HTML是否已设置。

例如,在提交表单时(假设它调用showMe()函数并停止使用.submit()手动提交表单),请使用document.cookie设置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变量$_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只允许在一个小提琴中使用一个php脚本,因此output.php中的代码必须移动到该PHP脚本的顶部,并且只有在有POST数据时运行(例如来自AJAX请求)。否则,文件中的代码可以保持独立。

相关问题