如何将回调函数中的值返回给调用者?

2022-01-19 00:00:00 return callback javascript ajax

如何让这个小函数imageExists"返回 ajax 请求是否成功?

How can i make this little function "imageExists" return wether the ajax request was successful or not?

function imageExists(path){
    $.ajax({
        url: path,
        type: 'HEAD',
        error:
            function(){
                return false;
            },
        success:
            function(){
                return true;
            }
    }); 
}

推荐答案

我相信你必须使用同步模式并使用单独的a变量来存储返回值.

I believe you'll have to use synchronous mode and use a separate a variable for storing the return value.

function imageExists(path){
    var isSuccess;
    $.ajax({
        url: path,
        type: 'HEAD',
        async: false,
        error:
            function(){
                isSuccess = false;
                return false;
            },
        success:
            function(){
                isSuccess = true;
                return true;
            }
    });
    return isSuccess;
}

相关文章