-3

如何用Javascript(在服务器上)写入文件?

我还需要阅读文件。这是我的代码:

function write()
{
var = true;
if( var = true)
{
//write file
    }
}
function read()
{
//read file
}
4

3 回答 3

0

您可以通过可能带有文件名或 id 的 AJAX 请求来读取文件

var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
    window.console.log(this.response);
}
xhr.open('GET','/readfile.php?id=1234');
xhr.send();

您可以通过从可能的文本类型输入中获取数据来编写文件。假设输入 id 为“文本”

var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
    window.console.log(this.response);
}
xhr.open('POST','/write.php');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send("id=someid&text=" + document.getElementById("text").value);

在 php 端只需获取发布数据并将其写入文件

$id = $_REQUEST["id"];
$text = $_REQUEST["text"]
$file = fopen($id . ".txt","w"); // you can change w to a incase you want to append to existing content in the file
fwrite($file,$text);
fclose($file);

如果您希望 Javascript 进行读取或写入,据我所知,只有 HTML5 文件 API,但我猜这仅用于读取文件。

于 2012-05-26T19:29:16.143 回答
0

如果我正确理解了您的问题,您希望在服务器中读取/写入文件,并且您的服务器端语言是 javascript。如果您使用的是 Node,此链接:http ://nodejs.org/api/fs.html#fs_fs_readfile_filename_encoding_callback 提供了有关执行相同操作的相关信息。

于 2012-05-26T19:34:11.533 回答
0

编写文件不是 Javascript 的特性。在最近的一些浏览器中,您已经可以阅读它们,但这不是一个好的选择。最好的方法是使用 PHP 读取它并使用 XMLHttpRequest 获取响应。

JavaScript

var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
    window.console.log(this.response);
}
xhr.open('GET','/fileReader.php?fileName=foo.txt');
xhr.send();

PHP

$content = file_get_contents($_GET['fileName']);
if($content)
    echo $content;
else echo "The file could not be loaded"
于 2012-05-26T19:14:46.203 回答