从jQuery的$ .ajax中嵌套的success-function返回值?

时间:2013-03-08 12:12:36

标签: javascript jquery ajax nested return-value

我发现这个问题几乎完全相同:Return value from nested function in Javascript

问题是该函数被传递给jQuery的$.ajax函数。这就是我所拥有的:

function doSomething() {
    // Do some stuff here
    console.log(getCartInfo());
}

function getCartInfo() {
    var url = blog_location + '?reqCartData=1';

    $.ajax({
        url: url,
        type: 'get',
        success: function(data) {
            return data;  <------------- This
        }
    });
}

如果有意义,我需要将data返回到doSomething函数。我试图返回整个$.ajax函数但返回整个对象。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

发送回调函数:

function getCartInfo(onSuccess) {
    var url = blog_location + '?reqCartData=1';

    $.ajax({
        url: url,
        type: 'get',
        success: function(data) {
            onSuccess(data);
        }
    });
}

getCartInfo(function(data) {
    console.log(data);
});

答案 1 :(得分:0)

试试这个

 function doSomething(date) {
    ........your data
}

function getCartInfo() {
    var url = blog_location + '?reqCartData=1';

    $.ajax({
        url: url,
        type: 'get',
        success: function(data) {
           doSomething(data);
        }
    });
}