单击按钮更新文本文件 [英] Update text file on button click

查看:85
本文介绍了单击按钮更新文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个有按钮的网站,然后单击它即可更改一些文本(说对/错).用户单击按钮时,文本必须更改,而不仅仅是网站上的每个用户,而且不仅仅是一个用户.

I want to make a website where there is a button, and when you click it make it change some text (saying either true/false). The text must change when the user clicks the button, but not just for the one user, for every user that's on the site.

我尝试执行此操作的方法是拥有一个文本文件,到目前为止,我所获得的只是页面上的一些文本,每500毫秒刷新一次以显示文本文件中的内容.

The way I'm trying to do it is I have a text file, and so far all I've got is some text on the page that every 500 milliseconds is refreshing to display whatever is in the text file.

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

So now all I need to do is update the text file when the button is clicked. What's the best way I could do this? (I want to be able to press the button on the computer hosting the site OR another computer accessing the site.)

谢谢, Fjpackard.

Thanks, Fjpackard.

更新

index.php:

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:

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();
    }
?>

推荐答案

您将在服务器上读取一个名为"file.txt"的文件.

You will be reading a file on the server with the name "file.txt".

假设您有以下代码可每500毫秒刷新一次页面:

Let's say you have this code to refresh the page each 500 milliseconds:

<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()">

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

So now all I need to do is update the text file when the button is clicked. What's the best way I could do this? (I want to be able to press the button on the computer hosting the site OR another computer accessing the site.)

script.php:

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();
    }
?>

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

This is the server side code that updates the file.

index.php

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请求,以从按钮的事件处理程序中执行该代码.

And here we are making an ajax request to execute that code from the event handler of the button.

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

Note: the code $.post(url, {}) will make the request. In this case we are not using the done continuation (that would be executed when the server sends its response) to avoid a race condition with the timer.

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

So far you have been reading file.txt. You could take advantage of script.php to provide the current value. That will be done in a GET request instead of a POST.

script.php:

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:

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进行读取和写入.这有助于在服务器上进行检查.例如:也许并非所有用户都可以更新或检索值.

As you can see, we are now using script.php both to read and to write. This facilitates doing checks on the server. For example: maybe not all users are allowed to update the value or to retrieve it.

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

Note: There is a race condition on the saver. If two clients makes requests on the server "at the same time" their updates on the file will overlap and the result will look like only one update happened (instead of two).

观察:

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

还要考虑:

  1. 使用 Web套接字,该套接字提供了一种更加通用的机制来将通知推送到客户端.有一些用于此的库,请参见问题是否可以使用Web Sockets的本机PHP支持?此处提出了一些替代方案. /li>
  2. 使用一种存储格式(例如ini,json,xml ...),使您能够在同一文件中存储更多信息.
  3. 使用数据库进行存储.数据库将解决服务器上的竞争状况,并提供存储更复杂数据的方法.数据库引擎不必是MySQL ...实际上,对于这种使用,基于文档的数据库可能是个更好的主意(尽管其中有些实际上支持SQL,但大多数通常被称为NoSQL).
  1. Using Web Sockets that provide a more versatile mechanism to push notification to the clients. There are some libraries for this, see the question Is native PHP support for Web Sockets available? where some alternatives are pressented.
  2. Using an storage format (such as ini, json, xml...) that will provide your the ability to store more info in the same file.
  3. Using a database for storage. Databases will solve the race condition on the server, and provide means to store more complex data. The database engine doesn't need to be MySQL... in fact, for this use a document based database may be better idea (most of them often refered as NoSQL, although some of them actually support SQL).

这篇关于单击按钮更新文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆