使用 Jquery $.get() 逐行检索文本文件
是否可以逐行检索txt文件内容?
现在我正在使用这段代码:
var file = "http://plapla.com/pla.txt";
function getFile(){
$.get(file,function(txt){
save(txt.responseText);
});
}
保存函数将内容保存到变量中。 当我打印出来后,检索到的文件的所有内容都在彼此的末尾(不是逐行)。
Is it possible to retrieve a txt files content line by line?
Right now I'm using this code:
var file = "http://plapla.com/pla.txt";
function getFile(){
$.get(file,function(txt){
save(txt.responseText);
});
}
the save function saves the content into a variable.
And after I print it out all the content of the retrived file is in the end of each other(not line by line).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定你的意思是当你打印出文件时,它会被全部推到一行上,或者你是说你想按行分割文件。
如果问题是当您显示它时,它会被推到一起,那只是因为您将其放入 HTML 页面中,这意味着换行符将被忽略。然后,您有两个选择,要么用
标记替换所有换行符,要么将所有文本放入前置标记中。如果您只想逐行处理数据,那么一旦收到数据,您就可以对它执行任何您喜欢的操作,就像逐行拆分一样。
I'm not sure if you mean that when you print out the file that it gets all pushed onto one line, or if you are saying that you want to divide the file by line.
If the problem is that when you display it, it gets pushed together, that is just because you are putting it into an HTML page, which means that newlines are ignored. You have two options then, either replace all of the newlines with
<br />
tags, or put all of your text in a pre tag.If you just want to work with the data line by line, then once you have received it, you can do whatever you like with it, just as splitting in up by line.
JavaScript 只能发出 HTTP 请求,这将返回带有全文的 HTTP 响应,不要通过打开套接字并逐行读取来理解逐行读取的想法。
但是,如果您的意思是逐行处理已读取的数据,您可以执行以下操作:
Javascript can only make a HTTP request, which would return you a HTTP response with the Full Text, do not get the idea of reading line-by-line with opening a socket and reading line-by-line.
However, if you mean treating the already read data line-by-line, you can do the following:
如果您尝试逐行显示(保留编码换行符),最简单的方法是将检索到的文本推送到 textarea 元素而不是 div (或类似元素)中。浏览器会智能地适当处理传入的文本。
自我更新:注意到这两种技术(data.replace() 或仅使用文本区域)似乎在 IE9 中不起作用。
If you're trying to display line-by-line (preserving encoded line breaks), the simplest way to do it is to push your retrieved text into a textarea element instead of into a div (or similar). The browser intelligently handles the incoming text appropriately.
Self-update: noticed that neither technique (data.replace() or just using a textarea) seems to work in IE9.