2015-02-23 93 views
1

我想知道是否有除了文件讀取api和XMLHttprequest()以外的任何方法來讀取/加載支持幾乎所有Web瀏覽器的文本文件。
我沒有使用xmlhttprequest(),因爲它不能在幾個瀏覽器中運行,比如chrome(因爲它有一個bug)you may find it here 我想知道純javascript/html方法,並希望避免使用php和django腳本。在html中閱讀文件

我嘗試以下方法XMLHttpRequest的

<!doctype html> 
<html> 
<head> 
    <body> 
    <script> 
    if (window.File && window.FileReader && window.FileList && winddow.Blob) { //alert('Great success! All the File APIs are supported.'); 
} 
    else { 
    alert('The File APIs are not fully supported in this browser.'); 
} 
var req = new XMLHttpRequest(); 
req.open('GET', 'text.txt'); 
req.onreadystatechange = function() { 
    if (req.readyState == 4) { 
    if (req.status == 200) { 
     var lines = req.responseText.split(/\n/g); 
     lines.forEach(function(line, i) { 
     alert(line); 
     }); 
    } else { 
     (alert("please update your browser,this webpage doesnt have  support for your browser")) 
    } 
    } 
} 
req.send(); 
    </script> 
    </body> 
</head> 
</html> 

這將運行在Firefox 35.0.1
但是當我嘗試在Chrome中使用它,它不工作
但是,如果我刪除的條件if(req.status==200)然後我收到一個沒有文字的警報。

+0

因此,運行chrome以允許文件訪問。 – epascarello 2015-02-23 03:12:53

+0

請向我們展示您到目前爲止的代碼。 – 2015-02-23 03:15:27

+0

啊,着名的http狀態碼。 200:「確定」,不是200:「更新瀏覽器」 – Winchestro 2015-02-23 06:23:49

回答

1

用戶控制的文件api和腳本化XMLHTTPRequest幾乎是唯一的選擇。另外,你可能有運氣與Java或閃光燈或Silverlight(等)的方法(我會留下來,現在的其他答案)。

替代爲自己的(發展)機:
對於鉻,你可以讓XMLHttpRequest的使用訪問其他文件的文件:
--allow-file-access-from-files
這將是至少安全,然後使用:--disable-web-security

另一個快速解決方案將是「微小」:https://www.ritlabs.com/en/products/tinyweb/download.php
我喜歡它,因爲它是!然後(通過環回ip或本地機器IP或主機名通過hostfile)我解決了這些限制,清除cookie /沙箱/本地存儲功能的路徑以及您正在嘗試解決的問題。

但是,這並沒有幫助一個簡單的可分發的HTML/JavaScript應用程序......正如你指出的,它目前是一個「不可修復」的鉻。

0

如果你有機會到文本文件,你可以編輯它是

var text = "ORIGINAL TEXT" 

和文件添加爲腳本標籤。