【问题标题】:Update text file on button click单击按钮时更新文本文件
【发布时间】:2014-01-14 16:33:19
【问题描述】:

我想制作一个有按钮的网站,当你点击它时,让它改变一些文本(说真/假)。当用户单击按钮时,文本必须更改,但不仅针对一个用户,还针对站点上的每个用户。

我尝试这样做的方式是我有一个文本文件,到目前为止,我所拥有的只是页面上的一些文本,每 500 毫秒刷新一次以显示文本文件中的任何内容。

所以现在我需要做的就是在单击按钮时更新文本文件。我能做到这一点的最好方法是什么? (我希望能够按下托管该站点的计算机或访问该站点的另一台计算机上的按钮。)

谢谢, Fjpackard。


更新

index.php:

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

<body>

<div id="theDiv"></div>

</body>

<script>

$("document").ready(function(){
    $("button").remove();
    setInterval(function(){
         $("#theDiv").load("file.txt");
    },500);
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
    if (agentID) {

        // mobile code here

    }
    else {
        $("body").prepend("<button>Toggle</button>");
        $("#theDiv").css("visibility","none");

        $("button").click(function(){
            myClick();
        });
    }
});

function myClick() {
                var url = ''; //put the url for the php
                value = $.post("", {}).done(
                    function(data) {
                        $('#theDiv').html(data);
                    }
                );
            }

</script>

script.php:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        $file = 'file.txt';

        $previous = file_get_contents($file);
        if ($previous === 'true')
        {
            file_put_contents($file, 'false');
            echo 'false'; //this is what we return to the client
        }
        else
        {
            file_put_contents($file, 'true');
            echo 'true'; //this is what we return to the client
        }
        exit();
    }
?>

【问题讨论】:

  • 你有什么尝试吗?有代码示例吗?
  • 我试过了:$fp = fopen('file.txt', 'w'); fwrite($fp, '假'); fclose($fp);并且:file_put_contents('file.txt','test');还没有运气:(
  • 我在Use buttons to post to a php script 看到了类似的结构。我会尽量适应你的情况。
  • 谢谢!怎么样了...? :)

标签: php jquery text-files overwrite


【解决方案1】:

单击该按钮会使用 jQuery 或简单的 javascript 发出一个 Ajax 请求。这将更新该文本文件。

如何在 jQuery 中发出 Ajax 请求: http://api.jquery.com/jquery.ajax

开心

【讨论】:

    【解决方案2】:

    您将在服务器上读取名为“file.txt”的文件。

    假设您有这段代码每 500 毫秒刷新一次页面:

    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        function myClick()
        {
            //somehow get and change the value
            /*var value = ???*/
            $('#theDiv').html(value ? 'true' : 'false');
        }
    
        $("document").ready(
            function()
            {
                setInterval(
                    function()
                    {
                        $("#theDiv").load("file.txt");
                    },
                    500
                );
            }
        );
    </script>
    <div id="theDiv"></div>
    <input type="button" value="click me" onclick="myClick()">
    

    所以现在我需要做的就是在单击按钮时更新文本文件。我能做到这一点的最好方法是什么? (我希望能够按下托管该站点的计算机或访问该站点的另一台计算机上的按钮。)

    script.php:

    <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST')
        {
            $file = 'file.txt';
    
            $previous = file_get_contents($file);
            if ($previous === 'true')
            {
                file_put_contents($file, 'false');
            }
            else
            {
                file_put_contents($file, 'true');
            }
            exit();
        }
    ?>
    

    这是更新文件的服务器端代码。

    index.php

    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        function myClick()
        {
            var url = 'script.php'; //put the url for the php
            $.post(url, {}); //avoiding using "done", let the timer update instead
        }
    
        $("document").ready(
            function()
            {
                setInterval(
                    function()
                    {
                        $("#theDiv").load("file.txt");
                    },
                    500
                );
            }
        );
    </script>
    <div id="theDiv"></div>
    <input type="button" value="click me" onclick="myClick()">
    

    这里我们发出一个 ajax 请求以从按钮的事件处理程序中执行该代码。

    注意:代码$.post(url, {}) 将发出请求。在这种情况下,我们没有使用 done 延续(将在服务器发送响应时执行)来避免与计时器的竞争条件。


    到目前为止,您一直在阅读file.txt。您可以利用script.php 来提供当前值。这将在 GET 请求而不是 POST 中完成。

    script.php:

    <?php
        // disable cache by HTTP
        header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
        header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');
        // disable cache by IE cache extensions
        header('Cache-Control: post-check=0, pre-check=0', false);
        // disable cache by Proxies
        header("Pragma: no-cache");
    
        $file = 'file.txt';
    
        if ($_SERVER['REQUEST_METHOD'] === 'POST')
        {
            // POST request
    
            $previous = file_get_contents($file);
            if ($previous === 'true')
            {
                file_put_contents($file, 'false');
            }
            else
            {
                file_put_contents($file, 'true');
            }
        }
        else
        {
            // not POST request, we assume it's GET
    
            echo file_get_contents($file);
        }
        exit();
    ?>
    

    index.php:

    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        function myClick()
        {
            var url = 'script.php'; //put the url for the php
            $.post(url, {});
        }
    
        $("document").ready(
            function()
            {
                setInterval(
                    function()
                    {
                        $("#theDiv").load('script.php');
                    },
                    500
                );
            }
        );
    </script>
    <div id="theDiv"></div>
    <input type="button" value="click me" onclick="myClick()">
    

    如您所见,我们现在使用script.php 来读写。这有助于在服务器上进行检查。例如:可能并非所有用户都可以更新或检索该值。

    注意:保护程序存在竞争条件。如果两个客户端“同时”在服务器上发出请求,他们对文件的更新将会重叠,结果看起来就像只发生了一次更新(而不是两次)。


    观察

    1. 您可能希望在服务器上进行其他检查,例如验证用户会话。也许不是每个人都能更新状态。
    2. 如果您想对同一 PHP 代码执行更多操作,您可能需要在 POST 请求中发送变量。在这种情况下,我们不这样做(我们只是发送{})。

    同时考虑:

    1. 使用Web Sockets 提供更通用的机制来向客户端推送通知。为此有一些库,请参阅问题Is native PHP support for Web Sockets available?,其中有一些替代方案。
    2. 使用一种存储格式(例如 ini、json、xml...),您可以在同一个文件中存储更多信息。
    3. 使用数据库进行存储。数据库将解决服务器上的竞争条件,并提供存储更复杂数据的手段。数据库引擎不需要是 MySQL...事实上,对于这种用途,基于文档的数据库可能是更好的主意(其中大多数通常称为 NoSQL,尽管其中一些实际上支持 SQL)。

    【讨论】:

    • 非常感谢您的帮助!尽管似乎仍然存在错误... :( 到目前为止,我将在原始帖子中附上代码。
    • @Fjpackard 显然您没有设置网址。请参阅代码中的 var url = '';,因为您决定为 php 使用不同的文件,您需要将其设置在那里:var url = 'script.php';。 [这是观察 #3] 编辑:我也犯了一个错误:我没有使用变量 url 反正:P - 已修复。
    • 好的,它几乎可以工作了!!当我单击计算机上的按钮时,它会更改我的 IPAD 上的状态,但在计算机上会出现一些故障。基本上在计算机上,每当它尝试切换到 FALSE 时,它就会变为 FALSE,然后很快又再次变为 TRUE,即使在我的 iPad 上它仍然是错误的......知道为什么会这样吗?
    • 好的,这很奇怪......现在似乎工作了!无论如何,感谢 A HEAP 的所有帮助 :):) 干杯,Fjpackard。
    • @Fjpackard 我想我明白发生了什么......点击的请求被发送并且定时器请求被发送,来自定时器的请求读取服务器上的值,然后值服务器由点击的持续请求更新,此请求返回并更新客户端上的值,计时器的请求将客户端上的值更新为在之前读取的错误值(但未显示)点击。由于服务器缓存,它甚至可能会在一段时间内保持错误的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多