简体   繁体   English

使用Javascript实时读取txt文件

[英]Read txt file real time with Javascript

I would like to know if there is some way to read a .txt file from Javascript in real-time? 我想知道是否有办法从Javascript实时读取.txt文件? I have a log file that updates every few seconds. 我有一个每隔几秒更新一次的日志文件。 I want to parse some data from that log file as it updates and display it in a html. 我想解析该日志文件中的一些数据,因为它更新并以html格式显示。 Can I do this live? 我可以直播吗? Thanks a lot guys! 非常感谢!

Assuming the file is somewhere publicly accessible, you can have a javascript function which makes an AJAX request every few seconds to read the file. 假设文件在某处可公开访问,您可以使用javascript函数,每隔几秒就会发出一次AJAX请求来读取文件。 Something like the following: 类似于以下内容:

function getLog() {
    $.ajax({
        url: 'logfile.txt',
        dataType: 'text',
        success: function(text) {
            $("#containerDiv").text(text);
            setTimeout(getLog, 30000); // refresh every 30 seconds
        }
    })
}

getLog();

No, you can't read/write a file with Javascript, cause it would be a terrible security issue. 不,你不能用Javascript读/写文件,因为这将是一个可怕的安全问题。

But, in your case, you can use some Ajax calls to a server-side script. 但是,在您的情况下,您可以对服务器端脚本使用一些Ajax调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM