使用jQuery:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
编辑:
下面是不使用jQuery判断404状态的代码
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
小的更改,它可以改为判断状态HTTP状态代码200(成功).
编辑2:由于sync XMLHttpRequest已被弃用,您可以添加这样的实用程序方法来异步执行:
function executeIfFileExist(src, callback) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
callback()
}
}
xhr.open('HEAD', src)
}