How can i return a value from a callback function to the caller?

前端 未结 3 2017
[愿得一人]
[愿得一人] 2021-01-22 16:22

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

function imageExists(path){
    $.ajax({
        url: p         


        
3条回答
  •  清歌不尽
    2021-01-22 16:50

    You're going to be returning the result of the AJAX call either in the success function or in the error function, so whatever function should be called next should be called from that point.

    Because an AJAX request is asynchronous (I'd advise not making it a blocking synchronous call), you make the request but don't know when it will return; it'll call you when it returns, so you just need to provide it something to call.

    function imageExists(path){
        $.ajax({
            url: path,
            type: 'HEAD',
            error:
                function(){
                    iveReturned(false);
                },
            success:
                function(){
                    iveReturned(true);
                }
        });   
    }
    
    function iveReturned(result) {
        // code here to do something following AJAX response.
    }
    

提交回复
热议问题