繁体   English   中英

如何使用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, event.preventDefault()防止form提交,在php encodeURIComponent() src设置为预期查询字符串的script元素作为encodeURIComponent()参数,在script onload追加script元素到head元素, onerror事件删除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请求。 这是一些使您入门的信息

您即将开始疯狂的旅程-cuz javascript并不容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM