javascript - PHP 认为它正在写入 .txt 文件,但实际上不是

标签 javascript php fwrite saving-data

我目前正在编写一个小网站,每个人都可以在其中设置是否出席。该网站的每个访问者都可以看到谁将出席、谁不在场。有一个小开关(一个带有 CSS 的复选框)指示存在。

我现在正在做的事情是一个开关(复选框),它将记住页面重新加载时的状态。我完成此操作的方法是写入服务器上的简单 .txt 文件“true”或“false”。启动时它读取文本文件的状态。我还添加了很多控制台注释来查看哪里出了问题,但现在我卡住了。

在注释末尾,当复选框更改时,它会使用 fread 读取 .txt 文件以检查 fwrite 是否有效。在控制台中,它说它写入正确(.txt 文件根据上次写入读取它应该读取的变量。)但是,如果我通过我的网站 www.example.eg/textfile.txt 访问该文件,它会说它没有' t改变了。此外,重新加载页面时不会保存复选框状态。

<!DOCTYPE html>
<html>
    <head>


        <script>
        function startupfunction(){
        <?php //reading current state
        $myfile = fopen("switchstate.txt", "r") or die("Unable to open file!");
        $output = fread($myfile,filesize("switchstate.txt"));

        // $output = "42";
        ?>

        var data = '<?php echo $output; ?>';
        var startupsetting;

        console.log("the initial (startupfunction) reading out of .txt(var = data):" + data);
        if(data == "true"){
            console.log("The if(true) statement based on var data works. setting bool to TRUE to change to correct switchstate")
            startupsetting = true;
        }
        else{
            console.log("The if(true) statement based on var data works. setting bool to FALSE to change to correct switchstate")
            startupsetting = false;
        }
        document.getElementById("myCheck").checked=startupsetting;
        console.log("This is done by setting a bolleaan called startupsetting this is now equal to:" + startupsetting);

        var x = document.getElementById("myCheck").checked;
        console.log("Now reading the state of the switch? did it work (is it equal to line above)" + x)
        } //close startupfunction


        window.onload = startupfunction;                    //set state of checkbox(switch)

        </script>
        </head>

<body>




<style>                                                                                             
    .onoffswitch {
    position: relative; width: 90px;
    -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
    display: none;
}
.onoffswitch-label {
    display: block; overflow: hidden; cursor: pointer;
    border: 2px solid #999999; border-radius: 20px;
}
.onoffswitch-inner {
    display: block; width: 200%; margin-left: -100%;
    transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
    display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px;
    font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
    box-sizing: border-box;
}
.onoffswitch-inner:before {
    content: "WEL";
    padding-left: 10px;
    background-color: #34A7C1; color: #FFFFFF;
}
.onoffswitch-inner:after {
    content: "NIET";
    padding-right: 10px;
    background-color: #EEEEEE; color: #999999;
    text-align: right;
}
.onoffswitch-switch {
    display: block; width: 18px; margin: 6px;
    background: #FFFFFF;
    position: absolute; top: 0; bottom: 0;
    right: 56px;
    border: 2px solid #999999; border-radius: 20px;
    transition: all 0.3s ease-in 0s; 
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
    margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
    right: 0px; 
}
</style>




<div class="onoffswitch">
    <input onchange="myFunction();" type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myCheck">
    <label class="onoffswitch-label" for="myCheck">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
</div>




<script>
function myFunction() {
    var x = document.getElementById("myCheck").checked;
    console.log("now starting measuring changes, x value changing...")
    console.log("Value of x before flipping:"+ x);
    x = (x) ? false : true;
    console.log("Value of x after flipping:" + x);

    //if(x==true) blaablaablaa
    if(x == true){
            <?php   //write 0 back to .txt file onserver
            $myfile = fopen("switchstate.txt", "w") or die("Unable to open file!");
            $txt = "false";
            fwrite($myfile,$txt);

            ?>

            console.log("wrote false(using the if/true statement) to .txt...");
            console.log("starting reading .txt file")

            <?php //reading current state
            $myfile = fopen("switchstate.txt", "r") or die("Unable to open file!");
            $output = fread($myfile,filesize("switchstate.txt"));

            // $output = "42";
            ?>

            var data = '<?php echo $output; ?>';
            console.log("the .txt file now reads:" + data);

    }

    else{
            <?php   //write 0 back to .txt file onserver
            $myfile = fopen("switchstate.txt", "w") or die("Unable to open file!");
            $txt = "true";
            fwrite($myfile,$txt);

            ?>
            console.log("wrote true(using the else/false statement) to .txt...");
            console.log("starting reading .txt file")

            <?php //reading current state
            $myfile = fopen("switchstate.txt", "r") or die("Unable to open file!");
            $output = fread($myfile,filesize("switchstate.txt"));

            // $output = "42";
            ?>

            var data = '<?php echo $output; ?>';

            console.log("the .txt file now reads:" + data);

    }


}
</script>
</body>
</html>

最佳答案

TL;DR 您需要加强客户端/服务器编程和 PHP 代码的 AJAX 回调。推荐有关 PHP 和 jQuery 的教程。我在这里冒险建议你看看http://www.w2ui.com用于界面开发(现在我会被每个人推荐他们最喜欢的框架或库而激怒;-))

<小时/>

您实际上需要两个 文件(至少)。只有第二个需要是 PHP。首先,在 Javascript 中,您拦截复选框更改。

这通常使用 jQuery 或类似的方法来完成,因为它使此类事情变得非常简单:

// this will only work if jQuery is loaded
$('#idOfMyCheckbox').on('change', function() {
    $.post(
        '/url/of/my/checkbox/saver',
        {
            state: $(this).val()
        },
        function(ret) {
            alert("The server replied: " + ret.message);
        }
    ).fail(function() {
        alert("something went very wrong");
    });
});

PHP 被 $.post 调用AJAX,并将收到$_POST['state']值。

<?php
     $fp = fopen("state.txt", "w");
     fwrite($fp, $_POST['state']); // DANGER WILL ROBINSON: NO ERROR CHECKING HERE.
     fclose($fp);
?>

调试

一旦您获得了应用程序,您需要知道它的实际用途。例如,加载上面的代码(一旦您为其提供了正确的 HTML、jQuery 绑定(bind)等)除了加载所需的资源之外,什么也不做。

然后,更改复选框的状态应触发到状态保存 URL 的 HTTP POST。

为了验证这一点,您会发现 Chrome 的 WebTools 或 Firefox 的 Firebug 扩展很有用。我猜自从您发出 console.log 以来您已经在使用类似的东西了来电。这些工具还记录资源使用情况和错误。

它们还允许您从控制台界面发出调用,这样您就可以运行

$('#idOfYourCheckbox')

并验证它返回一个只有一个对象的数组(否则,选择器会出现问题。例如,我通常复制并粘贴并最终得到 <input id="#myId"> 而不是 <input id="myId"> )。

然后您可以手动发出 .post调用,并验证它是否熄灭以及系统返回什么。上面,我没有费心添加 AJAX 查询所需的 JSON 返回:

 fclose($fp);
 Header("Content-Type: application/json;charset=utf-8");
 die(json_encode(array(
     'status'  => 'OK',
     'message' => 'It worked!',
 )));

(我这样做是出于懒惰。我的错。但这一切都表明您不应该期望只是在网站中插入一段代码并让它工作 - 您需要知道它的作用, 它应该做什么,即使这样,你也需要对它进行一些修改)。

独立示例(也带有状态加载)

<html>
    <head>
        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    </head>
    <body>
        <input id="mycheck" type="checkbox" />
    </body>
    <script>
        // jQuery main function
        jQuery(document).ready(function($) {

            /* Call this function on every change of myCheck.
               Since it is bound to #mycheck, inside the function
               'this' refers to the checkbox, and $(this) is the
               jQuery object mapping the checkbox.
            */
            $('#mycheck').on('change', function(e) {
                $.post(
                    'test.php',
                    {
                         cmd        : "set",
                         state      : $(this).prop("checked"),
                         timestamp  : new Date().getTime(),
                         hello      : "world"
                    },
                    function(reply, textStatus, jqXHR) {
                        if (!reply.hasOwnProperty('message')) {
                            console.log("the server replied with no message");
                            return;
                        }
                        console.log("the server replied: " + reply.message);
                    }
                ).fail(function(e) {
                    alert("Something went wrong");
                });
            });

            /* Now we also want to know what the status is NOW. */
            $.post(
                'test.php',
                {
                     cmd        : "get",
                     timestamp  : new Date().getTime()
                },
                function(reply, textStatus, jqXHR) {
                    if (!reply.hasOwnProperty('state')) {
                        console.log("the server replied with no state");
                        return;
                    }
                    // If the server replied TRUE we set state to true.
                    // Else to false.
                    $('#mycheck').prop('checked', reply.state);
                }).fail(function(e) {
                    alert("Something went wrong");
                });

        });
    </script>
</html>

PHP 端我们将在 test.php 中接收命令:

<!-- lang: lang-php5 -->
<?php
    function reply($reply) {
        Header("Content-Type: application/json;charset=utf-8");
        die(json_encode($reply));
    }
    function replyError($message) {
        return reply(array('status' => 'error', 'message' => $message));
    }
    function replySuccess($data, $message = '') {
        return reply(array_merge(
            array('status' => 'success', 'message' => $message),
            $data
        ));
    }

    array_key_exists('cmd', $_POST) || replyError('cmd not set');

    switch($_POST['cmd']) {
        case 'set':
            $fp = fopen('state.txt', 'w');
            $state = in_array($_POST['state'], array(1, "1", "true", true));
            fwrite($fp, $state ? "CHECKED" : "NOT CHECKED");
            fclose($fp);
            replySuccess(array('state' => $state));
        case 'get':
            if (!file_exists('state.txt')) {
                $state = false;
            } else {
                $text = file_get_contents('state.txt');
                $state = ('CHECKED' == $text);
            }
            replySuccess(array('state' => $state));
        default:
            replyError("cmd={$_POST['cmd']} is not recognized");
    }

关于javascript - PHP 认为它正在写入 .txt 文件,但实际上不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34311829/

相关文章:

javascript - jQuery 用户界面。创建后将 slider 值插入 block 中

javascript - 与不可点击的背景图片链接

javascript - jquery tabledit 下拉列表 : is it possible to retrieve values from mysql database?

c - fwrite问题,无法写入二进制文件!

c - 使用 fread/fwrite 在 C 中的文件中读写结构

javascript - 如何访问网格中的collapseTool的ID?

javascript - 未捕获 没有定义元素?

php - Dreamweaver 中 css 内的颜色代码 php

php - SQL更新查询集数量

c++ - fopen 并与磁盘同步