Php 如何在id为的特定div中获得ajax响应

Php 如何在id为的特定div中获得ajax响应,php,jquery,ajax,count,callback,Php,Jquery,Ajax,Count,Callback,对于简单的单击计数器,我使用以下代码: $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-c

对于简单的单击计数器,我使用以下代码:

$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/>

我的php(counter.php)

span元素的id数据单击id同名,该span元素的id应该为我提供新的编号,但这不起作用。我做错了什么


硬刷新后,该数字将增加1

$(id)
将不会选择任何内容,因为数据属性中的id是简单的字符串,如
click-001
。但这不是一个有效的选择器。您需要一个
#
来选择正确的位置。e、 g.
$(“#”+id)
这样最终的选择器看起来像
$(“#click-001”)
。(而且因为代码没有选择正确的元素,那么很明显页面上什么也不能输出。再加上Jay在下面的回答中的症状,PHP脚本可能不会总是输出任何东西,而且你有一个很好的方法来避免看到任何结果)。我同意<代码>成功:函数(数据){$(“#”+id).html(数据);},完成任务。Thnx for solution
$(id)
不会选择任何内容,因为数据属性中的id是简单的字符串,如
click-001
。但这不是一个有效的选择器。您需要一个
#
来选择正确的位置。e、 g.
$(“#”+id)
这样最终的选择器看起来像
$(“#click-001”)
。(而且因为代码没有选择正确的元素,那么很明显页面上什么也不能输出。再加上Jay在下面的回答中的症状,PHP脚本可能不会总是输出任何东西,而且你有一个很好的方法来避免看到任何结果)。我同意<代码>成功:函数(数据){$(“#”+id).html(数据);},完成任务。Thnx溶液
$('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!)                                                                  
        },

    });

});
$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);