“It is because I want to save the variable to be able to show it to all users on the website, so to do this I have the default value which is 1 and then I have a text input, which only allows numbers which are the variable+1 so lets say the default is 1, then I will put 2 into the input and then the .php file will get this input of 2 and save it into the .txt file, where after that the variable in the javascript will get this variable in the .txt file, and turn the new value into the variable. A bit complicated but basically it is just to save the variable for all users and not locally.”
好的,我很清楚你想在这里做什么.
重要的旁注:请仔细和完整地回答我的回答;我可能没有完全掌握你想要达到的目标,所以我的答案有两种选择.
这是你需要做的:
首先使用is_numeric()检查输入是否为数字.
然后分配变量并使用$_POST [‘variableToPass’]数组添加POST量.
PHP
if(isset($_POST['amount']) && is_numeric($_POST['amount']) ){
$amount = $_POST['amount'];
}
else{
echo "It is not numeric. Please click back and enter an integer.";
exit;
}
$variableToPass1 = $_POST['variableToPass'];
$variableToPass = $variableToPass1 + $amount;
$filename = "textFilePass.txt"; // make sure this file exists before executing
$content = file_get_contents($filename);
$content .= $variableToPass. PHP_EOL;
file_put_contents($filename, $content);
HTML表单
var variableToPass= 1;
document.getElementById("variableToPass").innerHTML = variableToPass;
document.getElementById("variableToPass").value = variableToPass;
但是,使用此方法将继续添加/附加到文件.如果这不是所需的结果,则需要删除以下点:
$content .= $variableToPass. PHP_EOL;
^
读作:
$content = $variableToPass. PHP_EOL;
另外,如前所述;这一行:
document.getElementByID("variableToPass").value = variableToPass;
应该读作:
document.getElementById("variableToPass").value = variableToPass;
> getElementById区分大小写.
选项2使用“amount”输入中的数字写入文件.
这将从输入中写入任何数字并将其写入文件,而不是附加到文件.
如果未插入数字且仅通过单击提交按钮,将写入您在var variableToPass = 1中定义的数字;
if(isset($_POST['amount']) && is_numeric($_POST['amount']) ){
$variableToPass = $_POST['amount'];
}
else{
$variableToPass = $_POST['variableToPass'];
}
$filename = "textFilePass.txt";
$content = file_get_contents($filename);
$content = $variableToPass. PHP_EOL;
file_put_contents($filename, $content);
脚注:
>如果您对此有任何疑问,或者我可能没有完全理解;让我知道.