weixin_33724059 2015-12-13 10:41 采纳率: 0%
浏览 24

AJAX内部回调成功

Im trying to add an optional callback inside an AJAX successful execution, but I can't seem to get the callback to run when I want it to.

heres and example of my AJAX code

function someAjaxFunction(hosturl, callback){
    $.ajax({
        type: "GET",
        url: hosturl,
        data: {'something': 'code' },
        dataType: 'json',
        success: function(html){                       
            var arr = $.map(html, function(val) { return val; });
            if(arr[0] != 'false'){
                console.log('1');
                console.log('2');
                if (callback) {
                    console.log('calling the callback')
                    callback();
                }
                console.log('3');
            }else{
               console.log('fail') 
            }   
        }
    });
}

here is the callback and example of how the AJAX is being executed

function thisIsACallBack(){
    console.log("i'm a callback");
}

someAjaxFunction("some url", thisIsACallBack);

If I run this code the console outputs.

1
2
3
i'm a callback

I can even remove the callback if-condition all together and I would still get the same output.

Also is here a better way to handle my Ajax return currently my response wrapped inside a json object. If the database can't find the object I have to place 'false' inside an array and convert it to a json object before echoing it back to ajax.

  • 写回答

1条回答 默认 最新

  • weixin_33727510 2015-12-13 10:46
    关注

    Couse you have to pass your callback as string to your function

    someAjaxFunction("some url", thisIsACallBack); // <-- Wrong thisIsACallBack will be triggered after someAjaxFunction as some separate function call
    

    like this

    someAjaxFunction("some url", "thisIsACallBack()"); // <- Correct way
    
    // Then call eval( callback ); inside Ajax success
    ....
    success: function(html){  
           ...
           eval( callback );
    }
    

    your problem was that in case of this code someAjaxFunction("some url", thisIsACallBack); it was triggering someAjaxFunction then thisIsACallBack function as you written someAjaxFunction name not as string

    UPDATE

    if you have to pass params to your callback your option is

    someAjaxFunction("some url", function(param1){ 
        thisIsACallBack(param1) 
    ); } );
    
    ...
    success: function(html){  
           ...
           callback( yourArray );
    }
    

    JavaScript has many ways how you can pass callbacks depends on your need

    评论

报告相同问题?