我使用 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>
输出.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() 阻止表单手动提交),请使用 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 只允许在 fiddle 中使用一个 php 脚本,因此 output.php 中的代码必须移至该 PHP 脚本的顶部,并且仅在存在 POST 数据(例如来自 AJAX 请求)时运行。否则,文件中的代码可以分开保存。
关于javascript - 如何停止使用 onload() 函数以避免页面刷新时丢失 PHP 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44266800/