2014-02-27 32 views
-2

我有以下代碼。在這我顯示正常的文字。代替我想我想在選擇下拉選項時顯示本地文本文件

加載本地文本文件。

我無法加載本地文本文件。

在這裏,我想從選擇選項a的textarea的我的主文件夾中加載a.txt文件的內容。等等。

<html> 
<body> 

<div class="left"> 
File Display 
<p> 

<select class="x" onchange="showfile(this);"> 

<option selected="selected" value="" id="Templates">Please select an option</option> 

<option>a</option> 

<option>b</option> 

<option>c</option> 

<option>d</option> 

</select> 

</p> 

<p> 

<textarea cols="30" rows="20" readonly="readonly" id="textar"> 

</textarea> 

</p> 

</div> 

<script> 

function showfile(sel){ 

files =[ "", 

/*option a*/     

"display file a.txt ", 

/*option b*/     

" display file b.txt ", 

/*option c*/     

" display file c.txt", 

/*option d*/     

"display file d.txt", ]; 

        srcfile = files [sel.selectedIndex];  

    if (srcfile != undefined && srcfile != "") {  

        document.getElementById('textar').innerHTML= srcfile; 

} 

} 

</script> 

</body> 
</html> 
+1

如果我理解正確你的問題,JavaScript不容許使用在本地系統上的文件訪問由於安全方面的原因。請閱讀此答案:http://stackoverflow.com/a/372​​333/1155208 – ninty9notout

+0

您需要j查詢Ajax(客戶端腳本)和PHP(服務器端腳本)。 j查詢將要求通過PHP獲取所有數據的Ajax。在PHP文件中,您需要編寫文件操作代碼來打開文件,讀取並顯示內容。 –

+0

它可以在django,python中完成嗎? – user1862399

回答

2

UPDATE

使用的FileReader API:

來源:

HTML

<div id="page-wrapper"> 

    <h1>Text File Reader</h1> 
    <div> 
     Select a text file: 
     <input type="file" id="fileInput"> 
    </div> 
    <pre id="fileDisplayArea"><pre> 

</div> 

JS

window.onload = function() { 
    var fileInput = document.getElementById('fileInput'); 
    var fileDisplayArea = document.getElementById('fileDisplayArea'); 

    fileInput.addEventListener('change', function(e) { 
     var file = fileInput.files[0]; 
     var textType = /text.*/; 

     if (file.type.match(textType)) { 
      var reader = new FileReader(); 

      reader.onload = function(e) { 
       fileDisplayArea.innerText = reader.result; 
      } 

      reader.readAsText(file);  
     } else { 
      fileDisplayArea.innerText = "File not supported!" 
     } 
    }); 
} 
+0

您可以向客戶端的本地文件系統發出AJAX請求?這不會破壞內置於JavaScript的安全規則嗎? –

+0

@ScorpionRulz嘗試改變這一行:'rawFile.open(「GET」,file,true);''rawFile.open(「GET」,file,false);' – LGSon

+0

@JayBlanchard根據它的工作原理。事情是你需要事先知道路徑,你不能查詢。 – LGSon