我试图创建一个按钮点击计数器,在每次下载时都会增加。我想在没有数据库的情况下使用它,这是代码:
<?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
。
知道问题出在哪里或有什么问题?
答案 0 :(得分:3)
重新加载到了被点击的链接(毕竟它仍然是一个链接,将重新加载页面)。
返回false:
jQuery(document).on('click','a#download',function(){
...
return false;
});
或使用preventDefault()
jQuery(document).on('click','a#download',function(e){
e.preventDefault()
...
});
您当前正在同一按钮上同时使用onclick=
属性和jQuery事件处理程序。那不是一个好的情况。
最好只为处理程序使用jQuery。 e.g。
jQuery(document).on('click','a#download',function(e){
e.preventDefault()
window.open(this.href);
... The other code ...
});
并从按钮中删除onclick="window.open(this.href);return false;"
。