我需要通过html和js代码实现在网页输入手机号和姓名点击提交后将信息保存在服务器上保存格式使用txt即可随后转跳至服务器的另一个html文件不使用php
要实现这个功能,你可以使用JavaScript的fetch API来将数据发送到服务器,然后使用Node.js来保存数据到txt文件。下面是一个简单的示例代码:
HTML文件(index.html):
<!DOCTYPE html>
<html>
<head>
<title>提交信息</title>
</head>
<body>
<h1>输入手机号和姓名</h1>
<input type="text" id="name" placeholder="姓名"><br>
<input type="text" id="phone" placeholder="手机号"><br>
<button onclick="submitForm()">提交</button>
<script src="script.js"></script>
</body>
</html>
JavaScript文件(script.js):
function submitForm() {
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var data = {
name: name,
phone: phone
};
fetch("/saveData", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(function(response) {
if (response.ok) {
window.location.href = "/success.html";
} else {
throw new Error("提交失败");
}
})
.catch(function(error) {
console.log(error);
});
}
Node.js服务器代码(server.js):
const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;
app.use(express.json());
app.post('/saveData', (req, res) => {
const data = req.body;
// 将数据保存到txt文件
const text = `姓名: ${data.name}\n手机号: ${data.phone}\n\n`;
fs.appendFile('data.txt', text, function(err) {
if (err) {
console.log(err);
res.status(500).send("保存数据失败");
} else {
res.sendStatus(200);
}
});
});
app.use(express.static('public'));
app.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});
在你的项目目录下创建一个名为public的文件夹,并在其中创建一个success.html文件,用于显示提交成功的页面。你可以根据需要自定义这个文件的内容。
这个示例使用Express框架来创建Node.js服务器,使用express.json()中间件来解析请求的JSON数据。服务器将数据保存到data.txt文件中。你可以根据需要修改文件名和保存方式。
确保你已经安装了Node.js和Express模块。在命令行中进入到项目目录,运行node server.js启动服务器。
然后,你可以在浏览器中打开index.html文件,输入手机号和姓名,点击提交按钮,数据将被发送到服务器并保存到txt文件中。随后会自动跳转到success.html页面
原文地址: https://www.cveoy.top/t/topic/itVj 著作权归作者所有。请勿转载和采集!