如何将文件内容获取到JavaScript变量中,以便进行处理?文件的大小可以高达3.5 MB,但可以轻松地分块处理,例如每次处理100行(1行为50-100个字符)。
文件的任何内容都不应对用户可见;他将看到数据处理的结果。
<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>
JavaScript:
<script type="text/javascript">
function LoadFile() {
var oFrame = document.getElementById("frmFile");
var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
while (strRawContents.indexOf("\r") >= 0)
strRawContents = strRawContents.replace("\r", "");
var arrLines = strRawContents.split("\n");
alert("File " + oFrame.src + " has " + arrLines.length + " lines");
for (var i = 0; i < arrLines.length; i++) {
var curLine = arrLines[i];
alert("Line #" + (i + 1) + " is: '" + curLine + "'");
}
}
</script>
注意:为了在 Chrome 浏览器中正常工作,您应该使用 --allow-file-access-from-files 标志启动它。来源。
加载大量数据并非明智之举,但如果你必须这样做,那么使用 jQuery 的 $.ajax()
函数可能是一种方案。
<html><head>
<script src="jquery.js"></script>
<script>
getTxt = function (){
$.ajax({
url:'text.txt',
success: function (data){
//parse your data here
//you can split into lines using data.split('\n')
//an use regex functions to effectively parse it
}
});
}
</script>
</head><body>
<button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button>
</body></html>
您需要使用Ajax,它基本上是向服务器发送请求,然后获取JSON对象,将其转换为JavaScript对象。
请检查以下内容:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
如果您正在使用jQuery库,它会更加容易:http://api.jquery.com/jQuery.ajax/
说了这么多,我强烈建议您不要将一个3.5MB的文件下载到JS中!这不是一个好主意。在服务器上进行处理,然后在处理后返回数据。然后,如果您想获取新数据,请发送新的Ajax请求,在服务器上处理请求,然后返回新数据。
希望这有所帮助。
我采用了Rafid的建议,使用了AJAX。
这对我很有用:
var url = "http://www.example.com/file.json";
var jsonFile = new XMLHttpRequest();
jsonFile.open("GET",url,true);
jsonFile.send();
jsonFile.onreadystatechange = function() {
if (jsonFile.readyState== 4 && jsonFile.status == 200) {
document.getElementById("id-of-element").innerHTML = jsonFile.responseText;
}
}
看起来XMLHttpRequest
已经被Fetch API所取代。谷歌发布了一篇很好的入门介绍,其中包含了一个实现你所需功能的例子:
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
然而,你可能想调用response.text()
而不是response.json()
。
有一个小细节,我看到一些答案使用了innerhtml。我曾经考虑过类似的想法,但最终决定不这样做,在最新版本的React中,同样的过程现在被称为dangerouslyinnerhtml,因为你通过在应用程序中呈现HTML来向客户端提供了进入操作系统的途径。这可能会导致各种攻击以及SQL注入尝试。
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
要进行设备文件读取,请使用以下内容:
readTextFile("file:///C:/your/path/to/file.txt");
要从服务器读取文件,请使用:
readTextFile("http://test/file.txt");
我真的认为你的方法是错误的。试图下载和解析一个超过3MB的文本文件是完全疯狂的。为什么不在服务器端解析文件,使用ORM将结果存储到数据库中(你可以选择SQL,但也取决于内容键值数据更适合像CouchDB这样的东西),然后使用ajax在客户端解析数据。
此外,如果可能的话,甚至更好的想法是完全跳过文本文件以获得更好的性能。
--allow-file-access-from-files
启动Chrome。 - EM0