如何返回到调用当前函数的函数

How to return to the function calling the current function

本文关键字:函数 调用 何返回 返回      更新时间:2023-09-26

如何返回到调用函数(上面的函数)。如果在执行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();
}

使用XMLHttpResponse作为异步。由于异步响应可能不会按照请求的顺序接收,而且您可能正在检查多个文件,因此在处理文件不"存在"(未找到或返回错误等)的情况之前,最好检查responseURL属性。

jsFiddle示例:http://jsfiddle.net/5f42L6nz/4/

来源:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

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");