我需要一个简单的解决方案,以在网页上动态显示更改文件的内容(某些计算的输出)。我提出了以下似乎可行的解决方案(确保有更好的解决方案)。不幸的是,由于output.txt
的内容未加载,因此无法达到预期的效果。可能我缺少一些基本知识。
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<style>
body {
font-family: monospace;
}
#target {
border: 1px solid gray;
min-height: 20em;
}
</style>
<h2>Yep</h2>
<textarea id="target" cols="60" rows="10">Loading...</textarea>
<script>
var checkInterval = 1; //seconds
var fileServer = "output.txt";
var lastData;
function checkFile() {
$.get(fileServer, function (data) {
// Update the text if it has changed
if (lastData !== data) {
$( "#target" ).val( data );
$( "#target" ).animate({
scrollTop: $( "#target" )[0].scrollHeight - $( "#target" ).height()
}, 'slow');
lastData = data;
}
});
}
$(document).ready(function () {
setInterval(checkFile, 1000 * checkInterval);
});
</script>
</body>
</html>
答案 0 :(得分:0)
此代码可以帮助您动态获取文件。
function read(){
jQuery.get('now.txt',function(data){document.write(data);});
}
如果您希望每3秒刷新一次,请使用setInterval
文档: