js判断文件是否存在的两种方法

[HtmlCssJs] 2024-03-28 圈点338

摘要:js判断文件是否存在的两种方法,方法1使用的是head,传递的内容较少,推荐;其使用的是ajax,兼容性更强。

js判断文件是否存在的两种方法:


jquery判断文件是否存在

function fileExists(url){

var isExists;

$.ajax({

url:url,

async:false,

type:'HEAD',

timeout:2000;

error:function(){

isExists=0;

},

success:function(){

isExists=1;

}

});

if(isExists==1){

return true;

}else{

return false;

}

}

用法var Exists=Exists('/cache/view_num/'+uid+'.txt');if(Exists){}


js判断文件是否存在:

function isExistFile(url)  

    {      

        var xmlHttp ;  

        if (window.ActiveXObject)  

         {  

          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  

         }  

         else if (window.XMLHttpRequest)  

         {  

          xmlHttp = new XMLHttpRequest();  

         }   

        xmlHttp.open("post",url,false);  

        xmlHttp.send();  

        if(xmlHttp.readyStatus==4){

            if(xmlhttp.status==200)return true;//url存在

            else if(xmlhttp.status==404)return false;//url不存在

            else return false;//其他状态

        }  

        return false;  

        else  

        return true;  

    }


方法1使用的是head,传递的内容较少,推荐;其使用的是ajax,兼容性更强。

  

相关内容:

感谢反馈,已提交成功,审核后即会显示