任何人都有一个示例代码,说明如何使用javascript
从/向文本文件读取和写入我尝试的是创建一个iframe并从iframe加载文本文件我读取内容并使用字符串操作进行一些更改,我不知道如何写回文本文件。 以及ie浏览器此代码无效。
我的text.txt文件包含 第一行 第二行 第三行 第四行
<html>
<head>
<title></title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--
var srcFrame;
function loadOuter(doc) {
srcFrame = document.getElementById("hiddenContent");
srcFrame.src = doc;
transferHTML();
}
function transferHTML(){
srcContent='';
if (srcFrame.contentDocument){
alert("document");
srcContent=srcFrame.contentDocument.getElementsByTagName("BODY")[0].innerHTML;
}
else if (srcFrame.contentWindow){
alert("window");
srcContent=srcFrame.contentWindow.document.body.innerHTML;
}
srcContent.length;
alert(" before push "+srcContent);
var arrayText="Last Line";
var lines = srcContent.split('\n');
lines=lines.slice(0, -1);
lines.push(arrayText,"</pre>");
lines = lines.join('\n');
srcContent=lines;
alert(srcContent);
document.getElementById("outerDisplay").innerHTML = srcContent;
}
</script>
<INPUT TYPE="button" VALUE="Test.txt" onClick="loadOuter('Test.txt')" >
<div id="outerDisplay"></div>
<iframe id="hiddenContent" width="200" height="200" style="position:absolute;visibility:hidden;" ></iframe>
</body>
</html>
答案 0 :(得分:1)
在IE中,这可以使用ActiveXObject和HTA。但是,建议仅使用本地,而不是WEB。请看:http://msdn.microsoft.com/en-us/library/ms536471%28v=vs.85%29.aspx
有关文件操作的更多信息:http://msdn.microsoft.com/en-us/library/bstcxhf7%28v=vs.84%29.aspx
以下基本功能:
ActiveXObject定义:
fso=new ActiveXObject('Scripting.FileSystemObject');
阅读文件:
iStream=fso.OpenTextFile('filePath',1,false);
iStream.ReadAll();
/* or looped iStream.ReadLine() */
iStream.Close();
写文件:
oStream=fso.OpenTextFile('filePath',2,true);
oStream.WriteLine(/*your_data*/);// This usually is looped according to your data
oStream.Close();
fso
- 对象也可以在常规的HTM页面中使用,但是要求您经常接受使用ActiveXObject。
答案 1 :(得分:0)
如果您正在谈论本地文件系统,Does HTML5 allow you to interact with local client files from within a browser
中涵盖了您的选项