How do I check if file exists in jQuery or pure JavaScript?

前端 未结 18 2125
闹比i
闹比i 2020-11-22 00:56

How do I check if a file on my server exists in jQuery or pure JavaScript?

18条回答
  •  臣服心动
    2020-11-22 01:21

    First creates the function

    $.UrlExists = function(url) {
    	var http = new XMLHttpRequest();
        http.open('HEAD', url, false);
        http.send();
        return http.status!=404;
    }

    After using the function as follows

    if($.UrlExists("urlimg")){
    	foto = "img1.jpg";
    }else{
    	foto = "img2.jpg";
    }
    
    $('').attr('src',foto);

提交回复
热议问题