文本计数问题


Problems with counting in text

尝试使用按钮和文本文件在 PHP 中计数时遇到问题。我在代码中看不到问题。

<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8">
 <script src="http://code.jquery.com/jquery-latest.js"></script>
 </head>
 <body>
   <div id="p">Click here</div>
   <div id="results"></div>
<script>
$('#p').click(function()
{
   $('#results').load("count.php");
});
</script>
 </body>
</html>

count.php 包含以下内容:

    <?php
    $clicks = file_get_contents("clicks.txt");
    $clicks++;
        $fp = fopen("clicks.txt", "w+");
        fwrite($fp, $clicks);
        fclose($fp);
//give the count to the user
echo "result: $clicks";
    ?>

从OP来看,您似乎希望为所有用户保留和累积此数据,因此服务器端组件是必要的。

以下是我对它的看法:
.HTML

<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    </head>
    <div id="p">Click here</div>
    <div id="results"></div>
    <script>
    $('#p').click(function()
    {
        $.ajax("count.php", {
                complete: function(jqXHR, status) {
                    $("#results").text(jqXHR.responseText);
                }
            })
    });
    </script>
    </body>
</html>

.PHP

<?php
   $clicks = intval(file_get_contents("clicks.txt"));
    $clicks++;
        $fp = fopen("clicks.txt", "w+");
        fwrite($fp, $clicks);
        fclose($fp);
//give the count to the user
echo "result: $clicks";

请注意,php 是相同的,但我现在从文件中获取 $clicks 值后将其更改为整数。

您还需要确保服务器的文件是可读/写的...在 Linux 中,您只需执行以下操作:

sudo chown -R www-data:www-data /var/www
sudo chmod -R g+rw /var/www

使您的www/目录(或将其更改为 Apache(?) 服务器使用的目录..)可由服务器读取/写入(这可能是矫枉过正,您可以使用相同的方法定位特定文件,只需删除 -R(递归)标志)。

在本地测试了此设置,它对我有用,祝你好运!

编辑:只是做个好人。

这是JS的no-jQuery解决方案(这不适用于所有浏览器,特别是较旧的IE版本,我会让你处理这些:P)

var p_btn = document.getElementById('p'),
    results = document.getElementById('results');
p_btn.addEventListener('click', function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET','count.php',false);
    xhr.onreadystatechange = function() {
        if( xhr.readyState === 4 && xhr.status === 200 ) {
            while(results.hasChildNodes()) {
                results.removeChild(results.lastChild);
            }
            results.appendChild(document.createTextNode(xhr.responseText));
        }
    }
    xhr.send();
}, false);
// enjoy!

现场演示

忽略从服务器吐出的添加代码。该死的免费主机