2013-05-21 36 views
0

使用javascript和node.js如何通过ajax将内容发布到文本文件。使用javascript和node.js如何通过ajax将内容发布到文本文件

<html> 
<body> 
    <input type="button" value="Click Me" onclick="postContent()"> 
    <script> 
    function postContent(){ 
     var req=new XMLHttpRequest(); 
     req.open('post','addContent.js',true);//in this sample.txt file i want to insert some content 
     req.send(); 
     } 

    </script> 
</body> 
</html> 

addContent.js

var fs = require('fs'); 
    fs.writeFile("/tmp/sample.txt", "Hey there!", function(err) { 
    if(err) { 
     console.log(err); 
    } else { 
    console.log("The file was saved!"); 
    } 
}); 

回答

0

你可以有一个服务器端脚本的内容写入到一个文本文件,并使用Ajax调用服务器端脚本。

req.open('POST', 'FilePoster', true); 
req.send(dataToWrite); 

编辑了新的问题:

req.open('post','addContent.js',true); 

addContent.js应该是一个主机和端口上运行的HTTP服务器。

如果addContent.js是一个节点的HTTP服务器,本地主机和端口8080上运行,公开征集应

req.open('POST', 'localhost:8080', true); 
+0

确定在服务器端脚本我有写代码的内容写入到一个文本文件。 – sachin

+0

@sachin请阅读更新的版本。 –

+0

好了,现在我明白了.. – sachin

相关问题