如何在 html 中使用 php 将文本框的值保存到.txt文件中,而无需重新加载或重定向页面


How to save the value of a textbox to a .txt file using php in html without reloading or redirecting the page?

我想在网页上制作一个文本框,该文本框将从用户那里获取一个数字,该数字将保存在.txt文件中。首先,我在 html 中制作了文本框并制作了一个表单。我创建了一个提交按钮来运行 php,并将其作为表单的操作。此php文件包含用于保存数据的代码。但是每当我尝试提交时,html都会刷新或重定向到php文件。但是我需要通过提交按钮保存文本框的值,而不是刷新整个页面。怎么办?以下是 html 的"表单"部分:

<form action="write2file.php" method="GET"/>
Iteration number:<br>
<input type="number" name="iteration_no"/>
<input type="submit" id="save_run" value="Run"/>
</form>

而 php 是:

<?php 
$filename ="noi_RS.txt";
$file = fopen( $filename, "w" );
fwrite( $file, $_GET['iteration_no']);
fclose( $file );
?>

修改了答案,修复了值存储为null的错误,

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js">    </script>
<script>
function callSubmit(){
var dataset = {"value1": document.getElementById('itnumber').value };
$.ajax({
   url: 'write2file.php',
   type: 'POST',
   data: dataset,
   success: function() {
      alert('Success');
   }
});
}
</script>
</head>
<body>
<form action="" method="GET" onsubmit="callSubmit()">
Iteration number:<br>
<input type="number" name="iteration_no" id="itnumber"/>
<input type="submit" id="save_run" value="Run" />
</form>
</body>
</html>

像这样的PHP文件,

<?php 
$text1 = $_POST['value1'];
$filename ="noi_RS.txt";
$file = fopen( $filename, "w" );
//$map = $_POST['iteration_no'];
fwrite( $file, $text1);
fclose( $file );
?>

尝试使用 onsubmit 事件 ,event.preventDefault() 防止form提交,创建script元素,src设置为预期的查询字符串,php作为参数encodeURIComponent()script元素附加到head元素,在script onloadonerror事件删除script元素

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <form>
Iteration number:<br>
<input type="number" name="iteration_no"/>
<input type="submit" id="save_run" value="Run"/>
</form>
  <script>
    document.forms[0].onsubmit = function(event) {
      event.preventDefault();         
      var val = this.children["iteration_no"].value;
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.onload = script.onerror = function() {
        console.log(this.src.split("?")[1]);
        this.parentNode.removeChild(this)
      };
      script.src = "?iteration_no=" + encodeURIComponent(val);
        document.head.appendChild(script);
    }
  </script>
    </body>
</html>

如果你想做一些像动态表单提交这样的事情,你需要使用javascript。

它的本质是您希望用户执行某些操作,然后在幕后响应该操作。对于用户,您可能只是告诉他们"嘿,我明白了"。

所以你需要javascript - 特别是你需要发送一个AJAX请求。以下是一些帮助您入门的信息。

你即将开始一段疯狂的努力之旅 - 因为javascript并不容易。