2016-03-08 39 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