如何返回调用函数(上面的函数)。如果在执行UrlExists('file.png')
时文件存在,我想返回true:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, true);
http.onerror = function(e){
//console.log('......onerror: ' + JSON.stringify(e));
if (typeof e !== 'undefined'){
return false
}
};
http.send();
return http.onerror();
}
答案 0 :(得分:0)
将XMLHttpResponse用作异步。因为可能无法按请求的顺序接收异步响应,并且由于您可能正在检查多个文件,因此在对文件不执行的情况下进行操作之前检查responseURL
属性可能是个好主意。 34;存在" (未找到或返回错误等)
jsFiddle示例:http://jsfiddle.net/5f42L6nz/4/
function UrlExists(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true); // true => async request
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// URL found, do stuff for "exists"
alert("url exists:\r\n" + xhr.responseURL);
} else {
// URL not found, could check xhr.status === 404, etc.
// do stuff when URL not found, but no exception/error thrown
alert("not found or unexpected response:\r\n" + xhr.responseURL);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
var url = '/'; // just an example, get web app root
UrlExists(url);
UrlExists("/badurl");