[英]Save form data to text file - HTML & Javascript
我不擔心安全性,這只是一個小項目,我只在我的電腦上使用。 我需要將帶有來自登錄表單的數據的 .txt 文件存儲到與 HTML 文件相同的位置。 我不認為你可以用 javascript 做到這一點,但我對 PHP 一無所知,我已經嘗試過很多次來讓它工作,但事實並非如此。 這是我的代碼。
<form style="text-align: center;" action="./success.html" method="post"> <div class="form-group"> <label for="username">Username</label> <input placeholder="Username" autocomplete="off" type="text" id="username" name="username"><br> </div> <div class="form-group"> <label for="password">Password</label> <input placeholder="Password" autocomplete="off" type="password" id="password" name="password"><br><br> </div> <input id="button1" class="btn btn-success" type="submit" value="Sign Up"> <,-- When pressed. needs to store data in a data.txt file. --> </form>
如果我使用此設置,我將如何做到這一點,我需要更改什么?
我將向您展示一個快速示例,以幫助您開始並創建一個 JSON 文件,其中包含以下數據:
{"username":"Lorem", "password":"ipsum"}
.txt
使用.json
文件。 它是當今最流行的結構化數據存儲和傳輸標准。file_put_content
fetch
("POST") 數據是FormData 使用php -S localhost:81
運行演示並在瀏覽器中打開它:
save.php
<?php
if (
$_SERVER['REQUEST_METHOD'] === 'POST'
&& isset($_POST["username"])
&& isset($_POST["password"])
) {
$json = json_encode($_POST);
// Save JSON to file
file_put_contents("user.json", $json);
// Return some data back to the AJAX request.
echo $json;
// PS it's not wise to send passwords that way.
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="#!" type="image/x-icon">
<title>AJAX PHP - SAVE USER DATA </title>
</head>
<body>
<h1>User: <span data-username>Unknown</span></h1>
<form id="form-login" action="./save.php" method="post">
<div class="form-group">
<label>
<span>Username</span>
<input placeholder="Username" autocomplete="off" type="text" name="username">
</label>
</div>
<div class="form-group">
<label>
<span>Password</span>
<input placeholder="Password" autocomplete="off" type="password" name="password">
</label>
</div>
<input id="button1" class="btn btn-success" type="submit" value="Login">
</form>
<script>
const EL_formLogin = document.querySelector("#form-login");
EL_formLogin.addEventListener("submit", (ev) => {
ev.preventDefault(); // Stop default form submit - we'll use AJAX
fetch(EL_formLogin.action, {
method: 'POST',
body: new FormData(EL_formLogin),
}).then(res => res.json()).then(data => {
// Hide the form
EL_formLogin.hidden = true;
// Show the user name
document.querySelector("[data-username]").textContent = data.username;
});
});
</script>
</body>
</html>
免責聲明!
切勿在服務器文件或數據庫中以明文形式存儲密碼 - 僅通過 HTTPS 發送密碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.