[英]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.