使用javascript检查服务器上是否存在html文件
我的ASPX代码生成了一些html文件,我只是在其中放置了分页链接,比如使用javascript检查服务器上是否存在html文件,javascript,html,Javascript,Html,我的ASPX代码生成了一些html文件,我只是在其中放置了分页链接,比如 <a href="1.html">First</a> | <a href="3.html">Next</a> | <a href="1.html">Previous</a> | <a href="9.html">Last<
<a href="1.html">First</a> |
<a href="3.html">Next</a> |
<a href="1.html">Previous</a> |
<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');
- @Sibu的解决方案存在一个问题:它实际上下载了文件(可能会很大,浪费流量)
- 2021年,新项目中有一个
- 土生土长,是今天的发展方向
//创建非缓存HTTP头请求
const fileExists=文件=>
获取(文件,{method:'HEAD',缓存:'no store'})
。然后(r=>r.status==200);
//检查服务器上是否存在文件
//并在给出响应后异步放置链接
const placeNext=file=>fileExists(文件)。然后(yes=>output.innerHTML=
(是?`:'')
);
//如果服务器上存在“3.html”,则在输出中放置“next”链接
placeNext('3.html');
您可以使用ajax请求站点,并检查状态代码是否为200。请记住,此答案使用的是Javascript库。:)
<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>