使用javascript检查服务器上是否存在html文件
Check html file exist on server using javascript
我的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>
如果用户当前在第二页上,按下"下一步"时移动到第三页。。。
现在的问题是,当用户多次点击"下一步"按钮,系统正在生成第五页时,它会显示错误页面。
有没有办法通过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>
相关文章:
- 使用javascript检查服务器上是否存在html文件
- HTML将数据保存在Access中
- HTML 中是否存在属性节点
- Html与php中的javascript似乎存在冲突
- 开箱即用的Light Switch HTML应用程序在IE9中存在null错误
- 是否存在非可视化HTML标记
- 仅当存在某些HTML元素时才运行多个Javascript脚本
- HTML画布保存在mysql数据库上
- 使用jQuery检查html元素中是否存在任何字符串
- 我如何才能检查HTML中是否存在这样的元素,它就是锚
- 在运行时添加复选框并将其保存在 HTML 文件代码中
- 将文件保存在 HTML 中的方法
- 检查屏幕上是否存在html项目
- 保存在html画布或网页中所做的更改
- 无法设置null错误的innerHTML.尽管存在html ID
- 在单元测试中检查指令中是否存在html元素
- 复选框和
- 为什么我不能用javascript迭代保存在html数据选择器上的这个数组?
- 使用HTML5 web存储将用户输入保存在HTML页面上
- 将数据保存在html标记属性中