|', $line); $count[trim($tmp[0])] = ...

问题描述 投票:0回答:1

对于一个简单的点击计数器,我使用这个代码。

$clickcount = explode("\n", file_get_contents('counter.txt'));
foreach($clickcount as $line){
    $tmp = explode('||', $line);
    $count[trim($tmp[0])] = trim($tmp[1]);
}

?>

<button class="click-trigger float-left" data-click-id="click-001">Click</button> 
<span id="click-001" class="click-count float-left"><?php echo $count['click-001'];?></span>
<br/><br/>

<button class="click-trigger float-left" data-click-id="click-002">Click</button> 
<span id="click-002" class="click-count float-left"><?php echo $count['click-002'];?></span>
<br/><br/>

<button class="click-trigger float-left" data-click-id="click-003">Click</button> 
<span id="click-003" class="click-count float-left"><?php echo $count['click-003'];?></span>
<br/><br/>

我通过ajax发送数据,如下图所示。

$('body').on('click', '.click-trigger', function (e) {
    e.preventDefault();

    var id = $(this).attr('data-click-id');

    $.ajax({
        url: 'counter.php',
        type: 'POST',
        data: { id:id },                    
        success: function(data){
           $(id).html(data);    // replace the new number in this div (but does not work!)                                                                  
        },

    });

});

我的 php (counter.php)

$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_POST['id']; 
$lines = '';
while(!feof($fh)){
    $line = explode('||', fgets($fh));
    $item = trim($line[0]);
    $num = trim($line[1]);
    if(!empty($item)){
        if($item == $id){
            $num++; // increment count by 1
            echo $num;  // send new number back to page     
            }
        $lines .= "$item||$num\r\n";
        }
    } 
file_put_contents($file, $lines);
fclose($fh);

身份证 的 span 元素的名称,它与 数据点击-ID 应该给我新的号码,但这不工作。我做错了什么?

在硬刷新后,数字增加了1。

php jquery ajax count callback
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.