This question already has answers here:
using javascript to detect whether the url exists before display in iframe

(5个答案)


3年前关闭。




如何检查文件夹中是否存在.html文件?我试图避免出现错误“可能已被移动或删除”。而是显示notFound.html
<body>
    <header>
        <form autocomplete="off">
            <input id="3Digits" type="number" min="100" placeholder="3-Digit Code">
            <span style="display:inline-block; width: 15px;"></span>
            <a href="#" id="goButton" onclick="check()">Go</a>
            <hr>
        </form>
    </header>
    <div id="frameDiv">
        <iframe id="srcCC"></iframe>
    </div>
    <script>
        var newLink
        function check() {
        newLink = document.getElementById("3Digits").value + ".html";
            if(newLink == ".html") {
                alert("You forgot to put the 3-Digit Code");
            }
            else {
                LinkCheck(newLink);
            }
        }
        function LinkCheck(url) {

            if(HTML EXISTS) {
                document.getElementById("frameSRC").src = newLink;
            }
            else {
                document.getElementById("frameSRC").src = "notFound.html";
            }
        }
    </script>
</body>

我要的是LinkCheck函数,所有文件都位于同一目录中。
这是一个小型学校项目,因此任何帮助将不胜感激!

最佳答案

您可以使用XMLHttpRequest检查文件是否存在

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

09-25 17:26
查看更多