使用JavaScript检查服务器上是否存在HTML文件

3
我的ASPX代码生成了一些HTML文件,其中我只放置了分页链接,比如:
<a href="1.html">First</a>&nbsp;|&nbsp;
<a href="3.html">Next</a>&nbsp;|&nbsp;
<a href="1.html">Previous</a>&nbsp;|&nbsp;
<a href="9.html">Last</a>

当用户按下“下一页”按钮时,如果用户当前在第二页,则转移到第三页...

问题是当用户多次点击“下一页”按钮并且系统正在生成第五页时,它将显示错误页面。

是否有一种通过JavaScript从HTML中检查文件是否存在的方法?请帮助我解决这个问题。


2
你可以使用 Ajax 请求网站,并检查状态码是否不是 200。 - GottZ
3个回答

6
您可以使用ajax来检查文件是否存在。
使用jQuery。
$.ajax({
        url:'http://www.example.com/3.html',
        error: function()
        {
           alert('file does not exists');
        },
        success: function()
        {
            alert('file exists');
        }
    });

使用Javascript

function checkIfRemoteFileExists(fileToCheck)
{
    var tmp=new Image;
    tmp.src=fileToCheck;

    if(tmp.complete)        
        alert(fileToCheck+" is available");        
    else        
     alert(fileToCheck+" is not available");        
}

现在要检查文件是否存在,可以像这样调用js函数:
checkIfRemoteFileExists('http://www.yoursite.com/abc.html');​

2
请记住,此答案使用 jQuery ,一个 JavaScript 库。 :) - Purag

2

我喜欢使用这种类型的脚本。

function CheckFileExist(fileToCheck: string) {

    return new Promise((resolve, reject) => {
        fetch(fileToCheck).then(res => {
            if (res.status == 404) resolve(false);
            if (res.status == 200) resolve(true);
            return res.text()
        }) 
    })

}

并使用它

 var exists = await CheckFileExist(link);

1
好的解决方案!不使用Typescript的人应该确保将第一行更改为“function CheckFileExist(fileToCheck) {”。 - René K

0
  • @Sibu的解决方案存在问题:它实际上下载了文件(可能很大,浪费流量)
  • 在2021年,新项目中不应该使用jQuery
  • 原生PromisesFetch是当今的首选
<output id="output"></output>

<script>
// create a non-cached HTTP HEAD request
const fileExists = file =>
  fetch(file, {method: 'HEAD', cache: 'no-store'})
  .then(r => r.status==200);

// check the file existence on the server
// and place the link asynchronously after the response is given
const placeNext = file => fileExists(file).then(yes => output.innerHTML = 
   (yes ? `<a href="3.html">Next</a>` : '')
);

// place the "next" link in the output if "3.html" exists on the server
placeNext('3.html');
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接