【发布时间】:2018-02-27 04:06:33
【问题描述】:
我想使用 JavaScript 和 PHP 向文本文档中添加文本。最好的方法是什么?
【问题讨论】:
标签: javascript php html
我想使用 JavaScript 和 PHP 向文本文档中添加文本。最好的方法是什么?
【问题讨论】:
标签: javascript php html
这可以通过使用 Javascript(前端)向执行操作的 PHP 服务器脚本(后端)发送 ajax 请求来实现。
您可以使用jQuery.ajax 或XMLHttpRequest。
XMLHttpRequestvar url = "addtext.php"; // Your URL here
var data = {
text: "My Text"
}; // Your data here
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
jQuery.ajaxvar url = "addtext.php"; // Your URL here
var data = {
text: "My Text"
}; // Your data here
$.ajax({
url: url,
data: data,
method: "POST"
})
注意:还有jQuery.post方法,不过我没有包含。
并且,在 PHP 文件中,具有必要的权限,您可以使用 fwrite 结合其他文件功能写入文件。
<?php
$text = $_POST["text"]; // Gets the 'text' parameter from the AJAX POST request
$file = fopen('data.txt', 'a'); // Opens the file in append mode.
fwrite($file, $text); // Adds the text to the file
fclose($file); // Closes the file
?>
如果你想以不同的模式打开文件,PHP网站上有a list of modes。
所有文件系统函数都可以在 PHP 网站上找到here。
【讨论】:
我不认为你可以追加到文本文档,除非你正在编写服务器端代码。
本文中提到了一些可能的解决方法: Is it possible to write data to file using only JavaScript?
【讨论】: