我有一个小提琴,当用户单击一个按钮时,计数器工作:http://jsfiddle.net/z66WF/。
这是代码:
<button type="button" onClick="clickME()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}问题是,我希望保存这个号码,例如:
我试图这样做,以跟踪一个文件被下载了多少次。
知道我该怎么做吗?
发布于 2014-11-12 16:43:08
这里有一个简单的例子,它将计数器写在一个简单的txt文件中(不需要sql db )。
<?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) ;
}
?>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<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>
</head>
<div id="counter"><?php echo $counter ; ?></div>
<a href="" id="download" onclick="window.open(this.href);return false;">Download btn</a>发布于 2014-11-12 16:23:02
为此,您需要一个DB连接。
当单击按钮时,任何用户都会使用1来增加"downloaded_times“的值。
因此,您需要一个查询,例如:
UPDATE table SET downloaded_times = downloaded_times + 1
每次有人按下按钮时,都会调用此查询。
如果您想要显示它,在某个用户想要开始下载之前,您只需从DB获取结果并返回它。如果您希望不断刷新该字段,则可以做更多的工作,抓取和回显部分应该位于名为PHP函数的ajax中,它将每30秒左右刷新div :D
希望这有帮助!
https://stackoverflow.com/questions/26891603
复制相似问题