JavaScript是跑在瀏覽器中,所以對於JavaScript讀取本地文件不想c++ 和 java那樣easy。網上有很多關於讀取本地文件的方法,許多是用ActiveXObject控件。ActiveXObject是微軟特有的,只能在IE內核的瀏覽器中運行,所以也不是一個好方法。
這里,介紹一種用Xml讀取本地文件的方法。
第一步:
Ngnix 服務器配置
下載ngnix(http://nginx.org/en/download.html), 解壓縮之后,打開nginx\conf\nginx.conf文件。配置root目錄為你的HTML腳本目錄。我的目錄是F:\webgl
啟動ngnix,(直接ngnix / ngnix –s reload)
1 listen 80; 2 server_name localhost; 3 4 #charset koi8-r; 5 6 #access_log logs/host.access.log main; 7 8 location / { 9 root F:\webgl; 10 index index.html index.htm; 11 }
第二步:
HTML代碼
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 9 <script !src=""> 10 11 function loadDoc() { 12 var xhttp = new XMLHttpRequest(); 13 xhttp.onreadystatechange = function() { 14 if (xhttp.readyState == 4 && xhttp.status == 200) { 15 for (var x in xhttp.responseText) { 16 console.log(xhttp.responseText[x]); 17 } 18 } 19 }; 20 xhttp.open("GET", "ajax_info.txt", true); 21 xhttp.send(); 22 } 23 24 loadDoc(); 25 26 </script> 27 28 </body> 29 </html>
運行結果:
文本內容

chorme瀏覽器運行結果

