【问题标题】:How to reload js without "window." or "location."如何在没有“窗口”的情况下重新加载 js。或“位置”。
【发布时间】:2018-07-07 18:00:14
【问题描述】:

我正在处理一个 js 文件。我需要 js 代码每隔几秒钟像新的一样运行。它不是一个网站,我不使用“窗口”。如果我想单独重新加载 js 代码,location.reload 不起作用。

我尝试了 setInterval。它使用缓存的内容。所以我没有得到准确的,当前的内容。如果我手动运行我的应用程序,每次运行我的应用程序时,我都会获得当前内容。但是如果我使用 setInterval,它只会抛出与第一次加载相同的值。是否有任何可用的 npm 包可以做到这一点或任何其他方式来做到这一点?感谢您的帮助。

这是代码:

var PythonShell = require('python-shell');
var pyshell = new PythonShell('demo.py');
var infy =[];
infy.length = 0;
var infyTBV; // Infy Total Buy Volume
// PythonShell.run('demo.py', function (err, results) {
//   if (err) throw err;
//   console.log(results);
// });
printinfy();

setInterval(function() { infyTBVfn(); }, 10000);

setInterval(function() { printinfy(); }, 10000);

function printinfy(){
pyshell.on('message', function (message){
    var mainstring = message.toString();
    // var substring = "totalBuyQuantity";
    infy.push(mainstring);
    // console.log("Inside loop: " + infy);
    // if(infy.includes("totalBuyQuantity")){
    //   infyTBV = message; 
    // }
});
}

function infyTBVfn(){

    var sno = 0;
        infy.forEach(function(element) {
    // console.log(sno+": "+element);
        if (sno == 63){
        infyTBV = element;
        console.log("outside loop: " + infyTBV);
    }
    sno++;
});
    // console.log("Number of items in var: "+infy.length);
}

我有另一个 python 文件,我正在从中读取内容。我正在使用“printinfy”函数从 python 文件中获取数据。

我将此文件命名为 demo.js。当我运行 node demo.js 时,每次运行它都会提供不同的值(这就是我想要的)。但是,如果我让它使用

自动打印出值

setInterval(function() { infyTBVfn(); }, 10000);

它打印的值与第一次打印时相同。

【问题讨论】:

  • 如果您更改代码,那么是的,您必须终止应用程序并重新启动它。如果您需要“当前内容”(无论您的意思是什么),您可以让您的代码读取文件的内容。
  • 如何终止并重新启动应用程序?
  • 你能告诉我们使用setinterval的代码吗?
  • 嗨 Mohammad,我已将详细信息和代码添加到问题中。感谢您的帮助。
  • 非常不清楚的问题。您需要准确解释实时更新什么类型的文件中的什么类型的内容。然后,也只有到那时,我们才能为您提供无需重新启动 node.js 脚本即可读取该内容的解决方案。您可能应该让您的 python 程序将数据放入 data 文件,而不是 JS 文件,然后您可以随时读取数据文件的最新副本。如果需要,可以使用 JSON 作为数据格式,并使用 JSON.parse() 解析数据。然后,您可以随时阅读该文件的最新副本。

标签: javascript node.js


【解决方案1】:

这里最好的解决方案是在 .js/.css 文件名的末尾添加时间戳

<script src="js/myfile.js?t=<?=time()?>" type="text/javascript"></script>

或者对于刷新 Div,您可以使用此示例

setInterval(function() {
    var baseDate       = new Date(),
        seconds        = baseDate.getSeconds(),
        secondsElement = document.getElementsByClassName("seconds")[0];
    secondsElement.innerHTML = seconds;
}, 1000);
<div class="seconds"></div>

 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多