如何使同步XMLHttpRequest变成异步?

huangapple go评论63阅读模式
英文:

Synchronous XMLHttpRequest last modified time, how to make it asynchronous?

问题

我找到了一段可以获取服务器上文件最后修改时间的代码,并进行了适应。它可以正常运行,但我收到了下面的警告,并了解到该代码可能会对用户的计算机造成资源压力。
代码需要对文件的修改做出反应(重新加载),并输出自上次修改以来的时间。
我注意到当我打开使用这段代码的两个窗口时,我的计算机会有些卡顿,也许这就是原因。

我该如何使这个异步?

"Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."

我发现了这个主题https://stackoverflow.com/questions/41008093/xmlhttprequest-is-deprecated-what-to-use-instead,我尝试修改了代码,但无法让这段代码给我最后修改的时间。
这只会返回 NaN

我需要帮忙将这个变成异步。我尝试阅读警告中的xhr链接,但我不是一个很擅长JavaScript的开发者,所以很难找到我需要做的事情。有人能指点一下我吗?

英文:

I found a code that could get the last modified time of a file on the server and have adapted it to my needs, it works fine but I get the warning below and reading about the code seems to be resource intensive for the users computer.
The code needs to react (reload) to a file being modified and print out the time since it was last modified.
I notice my computer is (slightly) sluggish when I have two windows open that use this code, perhaps this is the reason.

What can I do to make this asynchronous?

>Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/ .

       <script>
            var pageload = new Date();
            function fetchHeader(url, wch) {
                try {
                    var req=new XMLHttpRequest();
                    req.open("HEAD", url, false);
                    req.send(null);
                    if(req.status== 200){
                        return req.getResponseHeader(wch);
                    }
                    else return false;
                } catch(er) {
                    return er.message;
                }
            }

            window.setInterval(function(){
                var time = Date.parse(fetchHeader("Akut.txt",'Last-Modified'));
                var d = new Date();
                var diffSec = Math.round((d - time) / 1000);
                document.getElementById("time").innerHTML = Math.trunc(diffSec/60) + " minutes"; // time since it was modified
                
                if ((d-pageload)/1000 > 10 && diffSec < 5 ){
                    location.reload();
                }
            }, 2500);
        </script>

I found this thread https://stackoverflow.com/questions/41008093/xmlhttprequest-is-deprecated-what-to-use-instead and I have tried to modify the code but I can't get this code to give me the last modified time.
This just returns NaN.


             function fetchHeader(url, wch) {
                try {
                    var xhr = new XMLHttpRequest()
                    xhr.onreadystatechange = function() {
                        if (this.readyState === this.DONE) {
                            console.log(this.getResponseHeader(wch)); // assumed this would work but it doesn't
                        }
                    }
                    xhr.open("HEAD", url)
                    xhr.send()
                } catch(er) {
                    return er.message;
                }
            }

I need help with making this asynchronous. I have tried to read the xhr link from the warning but I'm not much of a Javascript developer so it's hard for me to find what I need to do.
Can someone point me in the right direction here?

答案1

得分: 1

这是异步XMLHttpRequest请求的代码部分:

const pageload = new Date(); // 页面加载时的时间
const url = "Akut.txt";
const whichHeader = "Last-Modified";
const compareTimeToNow = (time) => {
  let d = new Date();
  let diffSec = Math.round((d - time) / 1000);
  document.getElementById("time").textContent = Math.trunc(diffSec / 60) + " minutes"; // 自上次修改以来的时间
  if ((d - pageload) / 1000 > 10 && diffSec < 5) location.reload();
  else setTimeout(getHeader, 2500)
};

const getHeader = () => {
  const req = new XMLHttpRequest();
  req.addEventListener("load", reqListener);
  req.open("HEAD", url);
  req.send();
};

function reqListener() {
  console.log(this.responseText);
  compareTimeToNow(new Date(this.getResponseHeader(whichHeader)).getTime());
}
getHeader();

这是使用fetch的代码部分(适用于Chrome 42+、Edge 14+、Safari 10.1+、Firefox 39+和Opera 29+,不支持IE):

const pageload = new Date(); // 页面加载时的时间
const url = "Akut.txt";
const whichHeader = "Last-Modified";
const compareTimeToNow = (time) => {
  let d = new Date();
  let diffSec = Math.round((d - time) / 1000);
  document.getElementById("time").textContent = Math.trunc(diffSec / 60) + " minutes"; // 自上次修改以来的时间
  if ((d - pageload) / 1000 > 10 && diffSec < 5) location.reload();
  else setTimeout(getHeader, 2500)
};

const getHeader = () => {
  fetch(url)
  .then(rsp => compareTimeToNow(new Date(rsp.headers.get(whichHeader)).getTime()));
};

getHeader();
英文:

Here is the async xmlhttp request

<!-- language: lang-js -->
const pageload = new Date(); // when the page loaded
const url = "Akut.txt";
const whichHeader = "Last-Modified";
const compareTimeToNow = (time) => {
let d = new Date();
let diffSec = Math.round((d - time) / 1000);
document.getElementById("time").textContent = Math.trunc(diffSec / 60) + " minutes"; // time since it was modified
if ((d - pageload) / 1000 > 10 && diffSec < 5) location.reload();
else setTimeout(getHeader, 2500)
};

const getHeader = () =&gt; {
  const req = new XMLHttpRequest();
  req.addEventListener(&quot;load&quot;, reqListener);
  req.open(&quot;HEAD&quot;, url);
  req.send();
};

function reqListener() {
  console.log(this.responseText);
  compareTimeToNow(new Date(this.getResponseHeader(whichHeader)).getTime());
}
getHeader();

Using fetch (Chrome 42+, Edge 14+, Safari 10.1+ Firefox 39+ and Opera 29+ - no IE)

<!-- language: lang-js -->

const pageload = new Date(); // when the page loaded
const url = &quot;Akut.txt&quot;;
const whichHeader = &quot;Last-Modified&quot;;
const compareTimeToNow = (time) =&gt; {
  let d = new Date();
  let diffSec = Math.round((d - time) / 1000);
  document.getElementById(&quot;time&quot;).textContent = Math.trunc(diffSec / 60) + &quot; minutes&quot;; // time since it was modified
  if ((d - pageload) / 1000 &gt; 10 &amp;&amp; diffSec &lt; 5) location.reload();
  else setTimeout(getHeader, 2500)
};

const getHeader = () =&gt; {
  fetch(url)
  .then(rsp =&gt; compareTimeToNow(new Date(rsp.headers.get(whichHeader)).getTime());
};

getHeader();

huangapple
  • 本文由 发表于 2023年5月17日 18:54:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定