怎么用JS读写本地文本文件

JavaScript08

怎么用JS读写本地文本文件,第1张

采用jquery的ajax方式进行文件信息读取

代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<html>

<head>

<script type="text/javascript" src="/jquery/jquery.js"></script>

<script type="text/javascript">

$(document).ready(function(){

$("#b01").click(function(){

htmlobj=$.ajax({url:"/jquery/test1.txt",async:false})

$("#myDiv").html(htmlobj.responseText)

})

})

</script>

</head>

<body>

<div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>

<button id="b01" type="button">改变内容</button>

</body>

</html>

可以读取的,给你一个例子 自动写入和读取 D://js读取文本文件.txt

注意 只能在IE模式使用

<html>

<meta http-equiv="content-type" content="text/htmlcharset=gbk" />

<head>

<script language="javascript" type="text/javascript">

//读文件

function readFile(filename){

var fso = new ActiveXObject("Scripting.FileSystemObject")

var f = fso.OpenTextFile(filename,1)

var s = ""

while (!f.AtEndOfStream)

s += f.ReadLine()+"\n"

f.Close()

return s

}

//写文件

function writeFile(filename,filecontent){

var fso, f, s 

fso = new ActiveXObject("Scripting.FileSystemObject")

f = fso.OpenTextFile(filename,8,true)

f.WriteLine(filecontent)

f.Close()alert('ok')

}

</script>

</head>

<body>

该例子 将文件保存在D盘 D://js读取文本文件.txt

<input type="text" id="in" name="in" />

<input type="button" value="保存" onClick="writeFile('D://js读取文本文件.txt', document.getElementById('in').value)"/>

<br>

<br>

<input type="button" value="读取" onClick="document.getElementById('show').value=readFile('D://js读取文本文件.txt')"/>

<br>

<textarea id="show" name="show" cols="100″ rows="20″ ></textarea>

</body>

</html>