我正在尝试创建一个按钮点击计数器,每次下载都会增加。我想在没有数据库的情况下使用它,这是代码:
<?php
$counterFile = 'counter.txt' ;
// jQuery ajax request is sent here
if ( isset($_GET['increase']) )
{
if ( ( $counter = @file_get_contents($counterFile) ) === false ) die('Error : file counter does not exist') ;
file_put_contents($counterFile,++$counter) ;
echo $counter ;
return false ;
}
if ( ! $counter = @file_get_contents($counterFile) )
{
if ( ! $myfile = fopen($counterFile,'w') )
die('Unable to create counter file !!') ;
chmod($counterFile,0644);
file_put_contents($counterFile,0) ;
}
?>
<script type="text/javascript">
jQuery(document).on('click','a#download',function(){
jQuery('div#counter').html('Loading...') ;
var ajax = jQuery.ajax({
method : 'get',
url : '/test.php', // Link to this page
data : { 'increase' : '1' }
}) ;
ajax.done(function(data){
jQuery('div#counter').html(data) ;
}) ;
ajax.fail(function(data){
alert('ajax fail : url of ajax request is not reachable') ;
}) ;
}) ;
</script>
<div id="counter"><?php echo $counter ; ?></div>
<a href="<?php echo get_field("pdf"); ?>" id="download" onclick="window.open(this.href);return false;">Download btn</a>
问题是,当我单击Download btn
时,pdf会打开,但数字会消失,如果我重新加载页面,它总是保持在0
。知道问题在哪里或是什么吗?
重新加载取决于被单击的链接(毕竟它仍然是一个链接,这将重新加载页面)。
要么返回假:
jQuery(document).on('click','a#download',function(){
...
return false;
});
或者使用preventDefault()
阻止默认操作
jQuery(document).on('click','a#download',function(e){
e.preventDefault()
...
});
您当前在同一按钮上同时使用 onclick=
属性和 jQuery 事件处理程序。这不是一个好情况。
最好只对处理程序使用 jQuery,例如
jQuery(document).on('click','a#download',function(e){
e.preventDefault()
window.open(this.href);
... The other code ...
});
,然后从按钮上取下onclick="window.open(this.href);return false;"
。