javascript讀寫本機文字檔

來源:互聯網
上載者:User

近日在工作中遇到了一個情況:一張純html的網頁,用它一條一條輸入資料,然後由JS運算出結果(這些資料多半都是臨時的,所以也沒考慮儲存到資料庫),每次用完後換台電腦或出去搞活動現場示範時,又得重新輸入一些資料,比較麻煩!市場部的同事要求最好能將在公司測試時一些臨時資料匯出來,到現場時,直接匯入就可以了。當時我的第一反應是利用用戶端js,把資料post到服務端儲存,再由js通過ajax方式載入服務端的資料--即用服務端中轉實現資料的匯出和載入。後來想了想,就是一些偶爾用用的小玩意兒,還要用到服務端編程未免太麻煩了,於是研究了下JS直接讀寫檔案,發現其實也可以實現:

 

{
function onclick()
{
function onclick()
{
function onclick()
{
this.style.display='none'; document.getElementById('Code_Closed_Text_185330').style.display='none'; document.getElementById('Code_Open_Image_185330').style.display='inline'; document.getElementById('Code_Open_Text_185330').style.display='inline';
}
}
}
}" id="Code_Closed_Image_185330" style="display: none">{
function onclick()
{
function onclick()
{
function onclick()
{
this.style.display='none'; document.getElementById('Code_Open_Text_185330').style.display='none'; getElementById('Code_Closed_Image_185330').style.display='inline'; getElementById('Code_Closed_Text_185330').style.display='inline';
}
}
}
}" id="Code_Open_Image_185330">Code
<script type="text/javascript"> 
/*
FileExists(filepath)是驗證檔案是否存在的方法,filepath是檔案路徑
OpenTextFile,第二個參數有三種方式,都是常量:
ForReading=1          以唯讀方式開啟檔案。 不能寫這個檔案。
ForWriting=2          以寫方式開啟檔案
ForAppending= 8       開啟檔案並從檔案末尾開始寫。
*/

var oFso,oFile,sFile,sContent;
sFile = "c:\\luckty.txt";

//寫檔案
oFso = new ActiveXObject("Scripting.FileSystemObject");  
oFile = oFso.OpenTextFile(sFile,2,true); //寫方式開啟
oFile.WriteLine("菩提本無樹,明鏡亦非台,本來無一物,何處惹塵埃!");      
oFile.Close();  

//讀檔案
oFile = oFso.OpenTextFile(sFile,1);  //唯讀方式開啟
sContent = oFile.ReadLine();
oFile.Close();  

document.write(sFile + "檔案內容為:<br/><br/>" + sContent);
</script>
</head>

 

FileSystemObject這東東,相信只要以前弄過asp的哥們,對它再熟悉不過了(想當初做asp編程的年代,幾乎就指望著FileSystemObject/Adodb.Recordset/Adodb.Connection這三個對象過日子^_^)

值得說明的是,利用ActiveX來操作,瀏覽器會給一個大大的安全警告,呵呵,所以本文中的方法不適合給客戶使用,自己人用用還可以。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.