近日在工作中遇到了一個情況:一張純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來操作,瀏覽器會給一個大大的安全警告,呵呵,所以本文中的方法不適合給客戶使用,自己人用用還可以。