2016-03-08 37 views
3

我在網頁中有一個div,我只需要加載文本文件的最後第n行。 例如:JQuery只加載一頁的最後n行

<div id="contentdiv" style="white-space: pre-wrap;">here comes the output of the logfile</div> 
<script> 
    $(function() { 
    $("#contentdiv").load("logs/logfile.log"); 
    }); 
</script> 

但我只需要最後5行的日誌文件。

回答

2

假設行分隔符是\n

使用load方法會限制你第一次加載的一切,然後刪除

嘗試

$("#contentdiv").load("logs/logfile.log", function(response){ 

    $("#contentdiv").html(response.split("\n").slice(-5).join("\n")); 

}); 

但是,這將顯示所有的行首先,然後只有最後5.

所以,你需要隱藏這個div第一

$("#contentdiv").hide(); 
$("#contentdiv").load("logs/logfile.log", function(response){ 

    $("#contentdiv").html(response.split("\n").slice(-5).join("\n")); 
    $("#contentdiv").show(); 

}); 

另一個選項可能是

$.get("logs/logfile.log", function(data) { 
    $("#contentdiv").html(data.split("\n").slice(-5).join("\n")); 
}) 

這與去年5行加載DIV只有一次。

+0

謝謝你的完整答案!我會在3分鐘內接受你的回答(新會員的時間限制) – yoano

+0

@yoano確定,很樂意幫忙。 – gurvinder372