使用javascript检查服务器上是否存在html文件

Check html file exist on server using javascript

本文关键字:存在 html 文件 是否 javascript 检查 服务器 使用      更新时间:2023-09-26

我的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中检查文件是否存在?请帮我退出这个节目停止问题

您可以使用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');​

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

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);
  • @Sibu的解决方案有一个问题:它实际上下载了文件(它可能很大,浪费了流量)
  • 2021年,不应在新项目中使用jQuery
  • 原生Promises和Fetch是今天的发展方向
<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>
相关文章: