Retrieve text file line-by-line using Jquery $.get()
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 开发者_JAVA百科the retrived file is in the end of each other(not line by line).
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.
var file = "http://plapla.com/pla.txt";
function getFile(){
$.get(file,function(txt){
save(txt.responseText.replace(/\n/g, "<br />");
});
}
// OR
var file = "http://plapla.com/pla.txt";
function getFile(){
$.get(file,function(txt){
save($("<pre />").text(txt.responseText));
});
}
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.
var file = "http://plapla.com/pla.txt";
function getFile(){
$.get(file,function(txt){
var lines = txt.responseText.split("\n");
for (var i = 0, len = lines.length; i < len; i++) {
save(lines[i]);
}
});
}
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:
lineByLine = readData.split("\n");
process(lineByLine[0]); // First line
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.
精彩评论