简体   繁体   English

检查本地 HTML 文件是否存在并加载

[英]Check if local HTML file exists and load it

I'm new to JavaScript.我是 JavaScript 的新手。 I'm trying to check if an HTML file exists on my local machine.我正在尝试检查本地计算机上是否存在 HTML 文件。

  • If exists → Load the HTML file and display it in browser.如果存在 → 加载 HTML 文件并在浏览器中显示。
  • If not exists → Load and display a PNG file in browser.如果不存在 → 在浏览器中加载并显示 PNG 文件。

Couldn't find documentation for this problem online.无法在线找到有关此问题的文档。

You can use an XMLHttpRequest您可以使用XMLHttpRequest

function LinkCheck(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status != 404;
}

U can use the fetch api and to mimic http request for local text files:您可以使用 fetch api 并模仿 http 对本地文本文件的请求:

(async () => {
  const response = await fetch('index.html');
  console.log(response.body);
})();

Other solution is to use FileReader class其他解决方案是使用 FileReader class

Check this out: https://www.javascripture.com/FileReader看看这个: https://www.javascripture.com/FileReader

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

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