2016-02-22 34 views
3

如何建立txt文件在javascript

if (window.XMLHttpRequest) 
 
{ 
 
    xmlhttp=new XMLHttpRequest(); 
 
} 
 
else 
 
{ 
 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
 
} 
 
xmlhttp.open("GET","t1.txt",false); 
 
xmlhttp.send(); 
 
xmlDoc=xmlhttp.responseText; 
 
xmlhttp.open("w","t1.txt"); 
 
xmlhttp.writeln('hai'); 
 
xmlhttp.close(); 
 
console.log(xmlDoc);

我會讀取使用XMLHttpRequest() t1.txt文件,我怎麼會寫在同一個文件中一些文字t1.txt

+0

見http://stackoverflow.com/questions/30563157/edit-save-self-modifying-html-document-format-generated-下載新文件html-javascript – guest271314

回答

8

你不能。不允許瀏覽器端JavaScript寫入客戶機,而不禁用大量安全選項。

相反,你可以使用此代碼

function downloadContent(name, content) { 
    var atag = document.createElement("a"); 
    var file = new Blob([content], {type: 'text/plain'}); 
    atag.href = URL.createObjectURL(file); 
    atag.download = name; 
    atag.click(); 
} 

downloadContent("t1.txt","hello world"); 
+0

像魅力一樣工作。謝謝! – pranavjindal999

+0

非常感謝.... –