- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在编写一个小网站,每个人都可以在其中设置是否出席。该网站的每个访问者都可以看到谁将出席、谁不在场。有一个小开关(一个带有 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/
我有一个加号/减号按钮,希望用户不能选择超过 20 个但不知道如何让它工作。我尝试使用 min="1"max="5 属性,但它们不起作用。这是我的代码和一个 fiddle 链接。https://jsf
我正在尝试复制顶部底部图,如示例 here但它没有正确渲染(紫色系列有 +ve 和 -ve 值,绿色为负值)留下杂乱的人工制品。我也在努力创建一个玩具示例来复制这个问题,所以我希望尽管我缺乏数据,但有
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 这个问题似乎与 help center 中定义的范围内的编程无关。 . 已关闭 6 年前。 社区去年审查了是
这个问题在这里已经有了答案: Adding two positive integers gives negative answer.Why? (4 个答案) 关闭 5 年前。 我遇到了一个奇怪的问题
有谁知道如何将字符串值类型 -4,5 或 5,4 转换为 double -4.5 或 5.4? 最佳答案 只需使用 Double.parseDouble(Locale, String); 糟糕,我很困
我正在尝试根据 TextBlob 分类插入一个仅包含“正”或“负”字符串的新数据框列:对于我的 df 的第一行,结果是 ( pos , 0.75, 0.2499999999999997)我想要' 正
我对 VBA 非常陌生,无法理解如何在一个循环中完成 2 个任务。我非常感谢您的帮助。 我已经能够根据第 3 列中的数据更改第 2 列中的数值,但我不明白如何将负值的字体更改为红色。 表格的大小每月都
欢迎, 我正在使用 jquery 通过 POST 发送表单。 这就是我获得值(value)的方式。 var mytext = $("#textareaid").val(); var dataStrin
double d = 0; // random decimal value with it's integral part within the range of Int32 and always p
我有这个字符串: var a='abc123#xyz123'; 我想构建 2 个正则表达式替换函数: 1) 用 '*' 替换所有确实有 future '#'的字符(不包括'#') 所以结果应该是这样的
我正在使用 DialogFragment。当用户从 Gmail 平板电脑应用程序的屏幕与下面示例图片中的编辑文本进行交互时,我希望正面和负面按钮保持在键盘上方。 在我的尝试中不起作用,这是我的 Dia
从组装艺术一书中,我复制了这句话: In the two’s complement system, the H.O. bit of a number is a sign bit. If the H.O
是否有更好更优雅的方法来实现下面的简单代码(diffYear、A 和 B 是数字): diffYear = yearA - yearB; if (diffYear == 0) { A = B
我正在设计一种语言,并尝试确定 true 应该是 0x01 还是 0xFF。显然,所有非零值都将转换为 true,但我正在尝试确定确切的内部表示。 每种选择的优点和缺点是什么? 最佳答案 没关系,只要
在我的 dialogfragment 类的 OnCreateDialog 中,我正在这样做: AlertDialog.Builder builder = new AlertDialog.Builder
这个问题在这里已经有了答案: Resolving ambiguous overload on function pointer and std::function for a lambda usin
我偶然发现了一个奇怪的 NSDecimalNumber 行为:对于某些值,调用 integerValue、longValue、longLongValue 等,返回意想不到的值(value)。示例: l
这个问题在这里已经有了答案: Resolving ambiguous overload on function pointer and std::function for a lambda using
我有这个正则表达式来测试用户输入是否有效: value.length === 0 || value === '-' || (!isNaN(parseFloat(value)) && /^-?\d+\.
我想用高斯混合模型拟合数据集,数据集包含大约 120k 个样本,每个样本有大约 130 个维度。当我使用 matlab 执行此操作时,我运行脚本(簇号为 1000): gm = fitgmdist(d
我是一名优秀的程序员,十分优秀!