2016-02-22 4 views
3

как создать текстовый файл в 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);

Я читать t1.txt файл, используя XMLHttpRequest(), как я буду писать еще какой-нибудь текст в одном файле для t1.txt

+0

См http://stackoverflow.com/questions/30563157/edit-save-self-modifying-html-document-format-generated- html-javascript – guest271314

ответ

8

You не может. 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

спасибо, много человек .... –

Смежные вопросы