本文介绍了按钮单击计数器保存编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击计数器按钮时,我有这个小提琴:

I have this fiddle where when the user clicks a button the counter works: 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;
 }

问题是我希望保存号码,例如:

The problem is that I want the number to be saved, so for example:


  1. 用户#1点击按钮10次

  2. 用户#2打开网站,计数是10,他点击,现在计数器开始11

  3. 等等新用户。

我正在尝试这样做以跟踪文件下载的次数。

I'm trying to do this to keep track of how many times a file has been downloaded.

任何想法我该怎么做?

推荐答案

这里有一个简单的例子,它用一个简单的txt文件写入计数器(不需要sql db)

Here you have a working simple exemple, wich write the counter in a simple txt file (no sql db needed)

<?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>

这篇关于按钮单击计数器保存编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 18:54
查看更多