帮我写一个JS网页代码,要实现的功能是收集用户的输入的文字,在服务器上存储在一个TXT文件中
时间: 2024-03-21 12:39:44 浏览: 18
好的,以下是一个简单的实现方式:
1. HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>用户输入收集</title>
</head>
<body>
<h1>输入框</h1>
<input type="text" id="input" />
<button onclick="saveText()">保存</button>
<script src="saveText.js"></script>
</body>
</html>
```
2. JavaScript代码(保存在saveText.js文件中):
```javascript
function saveText() {
const input = document.getElementById("input").value;
const xhr = new XMLHttpRequest();
xhr.open("POST", "saveText.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send("text=" + input);
}
```
3. PHP代码(保存在saveText.php文件中):
```php
<?php
$text = $_POST['text'] . "\n";
$file = fopen("input.txt", "a");
fwrite($file, $text);
fclose($file);
echo "保存成功!";
?>
```
在上面的代码中,我们通过XMLHttpRequest对象向服务器发送POST请求,将用户输入的文本内容发送到saveText.php脚本。在saveText.php脚本中,我们将文本内容追加到input.txt文件中,并返回一个成功的消息。