html5 json表单储存,将表单数据存储到json文件中
时间: 2023-10-29 10:12:30 浏览: 40
可以使用 JavaScript 的 FormData 对象来获取表单数据,然后将其转换为 JSON 格式的数据,最后使用 Ajax 的方式将数据发送到服务器,服务器再将其以 JSON 格式的方式存储到文件中。
以下是一个简单的示例代码:
HTML 代码:
```html
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<button type="button" onclick="submitForm()">Submit</button>
</form>
```
JavaScript 代码:
```javascript
function submitForm() {
var formData = new FormData(document.getElementById("myForm"));
var jsonData = {};
for (var pair of formData.entries()) {
jsonData[pair[0]] = pair[1];
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "save-form-data.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(JSON.stringify(jsonData));
}
```
在服务器端,可以使用 PHP 脚本来接收数据并将其存储到 JSON 文件中:
```php
<?php
$data = json_decode(file_get_contents('php://input'));
$file = 'form-data.json';
$current = file_get_contents($file);
$current .= json_encode($data) . "\n";
file_put_contents($file, $current);
?>
```
注意:此代码仅供参考,具体实现需要根据实际情况进行调整。