为了账号安全,请及时绑定邮箱和手机立即绑定

JS 没有响应更新的 txt 文件

JS 没有响应更新的 txt 文件

PHP
慕桂英3389331 2022-07-09 18:09:33
目标:后台循环会不断读取并打印文件(word.txt)按下其中一个按钮将覆盖其中的值word.txt然后后台循环将读取此更改并打印怎么了:后台循环不断读取并打印文件(word.txt)按下其中一个按钮会覆盖word.txt 但....中的值。 3. 在我继续在不同浏览器中访问“word.txt”文件并刷新页面之前,此更改不会反映在 JS 中。完成后,JS 开始识别它。有任何想法吗?抱歉,该代码段无法正常php工作var instanse = false;var state;var mes;var file;console.log('update.js loaded');function triggerUpdate(){    console.log('update.js is triggered');    updateChat();}//Background Loopfunction updateChat(){            var file = 'word.txt';            var rawFile = new XMLHttpRequest();            rawFile.open("GET", file, false);            rawFile.onreadystatechange = function ()            {                if(rawFile.readyState === 4)                {                    if(rawFile.status === 200 || rawFile.status == 0)                    {                        var allText = rawFile.responseText;                        console.log(allText);                    }                }            }            rawFile.send(null);    setTimeout(updateChat, 1500);}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><!DOCTYPE html><html><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Random Word Generator</title>    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>    <script type="text/javascript"></script>    <script language="javascript" src="update.js" type="text/javascript"></script></head><body onload="triggerUpdate();">    <form action="" method="post">    <input type="submit" name="word"                class="button" value="Button1" id="button1"/>                   <input type="submit" name="word"                class="button" value="Button2" id="button2"/>     </form>
查看完整描述

1 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

浏览器正在缓存调用的初始结果XMLHttpRequest。最简单的解决方法是通过将随机数作为参数附加到 url 来欺骗缓存。文件系统在查找文件时会忽略它。

您可以添加任何您想要的查询变量('v' 很流行 - 有点代表版本)。

有很多方法可以获得随机数,但使用 Unix 时间戳 - Date.now() - 是一种简单的方法,在这种情况下应该可以解决问题。

更改代码:

var file = 'word.txt';

至:

var file = 'word.txt?v=' + Date.now();

这将创建对这样的 url 的调用:word.txt?v=1519211809934



查看完整回答
反对 回复 2022-07-09
  • 1 回答
  • 0 关注
  • 94 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信