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

前端 未结 3 2062
[愿得一人]
[愿得一人] 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:58

    Create a var to hold the response on a global level, then set async to false. You need to then set that var in the success or error function.

    http://api.jquery.com/jQuery.ajax/

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

提交回复
热议问题