Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 the retrived file is in the end of each other(not line by line).

like image 920
karq Avatar asked Jun 30 '11 13:06

karq


1 Answers

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]);
        }
    }); 
}
like image 82
loganfsmyth Avatar answered Sep 27 '22 22:09

loganfsmyth