日期:2014-05-16  浏览次数:20358 次

JS 操作文件(FF不兼容)

<html>
<head>
<title>JS操作文本文件</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>

<script>
var arr = new Array();
arr[0] = [0,"name0","value0"];
arr[1] = [1,"name1","value1"];
arr[2] = [2,"name2","value2"];
arr[3] = [3,"name3","value3"];
arr[4] = [4,"name4","value4"];
function Write2Text()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f = fso.CreateTextFile("a.txt", true);
for(var i=0;i<arr.length;i++)
{
f.write(arr[i])
f.WriteBlankLines(1)
}
f.Close();
}
</script>
<input type=button value="Write" onclick="Write2Text()">



<script>
	function GetHeader(src) {
		var ForReading=1;
		var fso=new ActiveXObject("Scripting.FileSystemObject");
		var f=fso.OpenTextFile(src,ForReading);
		return(f.ReadAll());
	}
	function ReadText(){
		var arr=GetHeader("a.txt").split("\r\n");
		for(var i=0;i<arr.length;i++){
			alert("第"+(i+1)+"行数据为:"+arr[i]);
		}
	}
</script>

<input type=button value="Read" onclick="ReadText()">

</body>
</html>




据说这是JS读取远程的文件.但是我没有测试过,贴于此仅供参考
<script type="text/javascript"><!--
//页面级XMLHttp对象
var xmlhttp;

//向服务器发送信息函数
function getPage(pageURL) {
    xmlhttp = createXMLHttp();
    if (xmlhttp)
    {
        xmlhttp.onreadystatechange = setPageData;
        xmlhttp.open('GET', pageURL);
        xmlhttp.send(null);
    }else{
        alert("XMLHttpRequest对象为空");
    }
}
//回调函数,获得从服务器回发的文档信息并显示在disp层中
function setPageData(){
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
         var word = bytes2BSTR(xmlhttp.responseBody);
       
         document.getElementById("disp").innerHTML = word ;
    }
}
//创建XMLHttp对象,用于读取远程文档
function createXMLHttp(){
    try {
        return new ActiveXObject ("Microsoft.XMLHTTP");
    }catch(e){
        try {
            return new XMLHttpRequest();
        }catch(e) {
            return null;
        }
    }
    return null;
}
// --></script>