不要开火了

时间:2015-07-24 09:52:04

标签: javascript jquery

$.ajax回调中,我想根据从服务器收到的内容执行操作,即发送truefalse
问题是,在代码中的某个地方,我想要重新开火并且它没有:

function check()
{
    // $.ajax callback(result)
    {
        console.log(result); //in this case I get 'true' (boolean)
        if(!result)
        {
            // I checked I don't end up here
        }
        else
        {
            console.log('well done'); // shows up in the console
            return "done";
        }
    }
    return "oops";
}

// later in the code
console.log(check()); // displays "oops" whereas the console.log('well done') has showned up in the console

我没有给你的部分功能主要是CSS效果。

你知道为什么return无法解雇,或者我错过了什么?提前谢谢!

1 个答案:

答案 0 :(得分:1)

您在回调中返回一个值,这就是为什么您没有获得此值,您的代码相当于:

function callback (result) {
    if (!result) { }
    else {
        console.log('well done') ;
        return "done";
    }
}

function _ajax (cb) {
    cb (true) ; // Call cb but does not care about the result
    return true ;
}

function check() {
    ajax (callback) ; // Call ajax but does not care about its result
    return "oops";
}

check () ;

如果您正在执行异步请求,行为会有所不同,但这个想法会保持不变。

您永远不应该进行同步(a)jax调用,但如果您不在乎,可以执行以下操作:

function check () {
    var res ;
    $.ajax ({
        success: function (result) {
            if (!result) { res = "fail" ; }
            else {
                console.log('well done') ;
                res = "done" ;
            }
        }
    }) ;
    return (typeof res === 'undefined') ? "oops" : res ;
}
相关问题