我编写了这段代码,以检查“上载”文件夹中是否存在名称相同的文件“计划”,但扩展名为pdf或html的文件。我知道,这种语法没有经过优化,但是可以工作。我认为有更短和更简单的方法。
有谁可以和我分享一些例子吗?
谢谢。
<script>
function FileExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
var source = "upload/planning_11";
var pdf_file = FileExist(source+".pdf");
var html_file = FileExist(source+".html");
if (pdf_file==true && html_file==false) {
$('#exist_file_pdf').show();
$('#exist_file_html').hide();
$('#exist_file_all').hide();
} else if (pdf_file==false && html_file==true) {
$('#exist_file_html').hide();
$('#exist_file_html').show();
$('#exist_file_all').hide();
} else if (pdf_file==true && html_file==true) {
$('#exist_file_html').hide();
$('#exist_file_html').hide();
$('#exist_file_all').show();
} else if (pdf_file==false && html_file==false) {
$('#exist_file_html').hide();
$('#exist_file_html').hide();
$('#exist_file_all').hide();
}
</script>
<div id="exist_file_pdf">PDF planning file exist</div>
<div id="exist_file_html">HTML planning files exist</div>
<div id="exist_file_all">PDF and HTML planning files exists !</div>
不要使用异步false
相反,您可以这样做
const source = "upload/planning_11";
const pdfUrl = source + ".pdf";
const htmlUrl = source + ".html";
$('#exist_file_all').hide();
$('#exist_file_html').hide();
$('#exist_file_pdf').hide();
$.ajax({
type: 'HEAD',
url: pdfUrl
success: function(msg) {
$('#exist_file_pdf').show();
$.ajax({
type: 'HEAD',
url: htmlUrl
success: function(msg) {
$('#exist_file_html').show();
if ($('#exist_file_html').is(":visible") &&
$('#exist_file_pdf').is(":visible")) {
$('#exist_file_all').show();
$('#exist_file_html').hide();
$('#exist_file_pdf').hide();
}
}
});
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句