我有一个页面action.php
,我在这个页面上通过代码运行SQL查询,这样每当查看页面时,查询就像一样运行,就像计算页面浏览量一样。
<?php
mysqli_query("UPDATE ****");
?>
问题是,当页面被刷新时,查询就会运行&页面刷新被算作页面视图,这是我想要避免的。
一个问题:如何避免它?
我正在寻找的是一个简单的解决方案,以便我可以检查
if( page was refresh ) //some condition
{
do
}
发布于 2010-11-27 14:19:29
我已经解决了这个问题。没有会话和cookie的HURRAHHH
这个解决方案是PHP : AJAX : JavaScript的组合
您希望在Page Load而不是page Refresh上运行的查询通过AJAX调用运行它,假设我的函数是
function runQUERY()
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","doIT.php",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
通过执行以下操作,我可以简单地使用Javascript检查页面是新加载的还是刷新的
<head>
<script type="text/javascript">
function checkRefresh()
{
if( document.refreshForm.visited.value == "" )
{
// This is a fresh page load
alert ( 'Fresh Load' );
document.refreshForm.visited.value = "1";
..call you AJAX function here
}
else
{
// This is a page refresh
alert ( 'Page has been Refreshed, The AJAX call was not made');
}
}
</script>
</head>
<body onLoad="checkRefresh()">
<form name="refreshForm">
<input type="hidden" name="visited" value="" />
</form>
</body>
</html>
在您的doIT.php中,简单地添加您要放入普通页面的PHP代码。
<?php
mysql_query("UPDATE---------");
//put any code here, i won't run on any page refresh
?>
发布于 2014-07-16 04:16:56
我找到了这个here片段,它非常适合我:
$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
if($pageWasRefreshed ) {
//do something because page was refreshed;
} else {
//do nothing;
}
发布于 2010-11-27 13:17:18
您不能直接检测页面刷新,但您可以使用cookie来模拟您想要的内容:
if (isset($_COOKIE['action'])) {
// action already done
} else {
setcookie('action');
// run query
}
根据您的要求,您还需要决定何时删除cookie和/或再次执行该操作。
https://stackoverflow.com/questions/4290230
复制相似问题