将AJAX调用的响应返回给其他函数

时间:2013-12-25 17:38:06

标签: jquery ajax jquery-callback

这是我的代码部分:

$("#edit-field-order-borispol-und").change(foo);        
function foo() {
var result;
var customerid = $( "#edit-field-order-customer-und" ).val();
    $.ajax({
        type: 'GET',
        url: '/ops',
        data: {'customerid': customerid},
        success: function(response) {
            result = response.borispol;
            alert(response.borispol);// this alerts the info that i NEED...
        }
    });
return result;
}
foo(function(result) {
    alert(result+' it works'); // cant make it to work...
    // code that depends on 'result'
});

我检查了这个: How do I return the response from an asynchronous call?

仍然......我无法弄清楚出了什么问题。请帮助我完全了解jquery ......

2 个答案:

答案 0 :(得分:0)

如果您希望当前代码开始工作,请尝试将属性async:false添加到$.ajax。而是

foo(function(result) {
    alert(result+' it works'); // cant make it to work...
    // code that depends on 'result'
});

应该是

function other_func(result) {
    alert(result+' it works');
    // code that depends on 'result'
};

但正如文章中所显示的那样,你联系了 - 这是不好的方式。

您最好将依赖于result的代码放入成功回调或类似

function foo() {
    var customerid = $( "#edit-field-order-customer-und" ).val();
    return $.ajax({
            type: 'GET',
            url: '/ops',
            data: {'customerid': customerid},
    });

}.done(function(response) {
    alert(response.borispol+' it works'); 
    //code that depends from  result (response.borispol) or anything else
});

但是!请注意done中的代码执行异步!

答案 1 :(得分:0)

支持@ Raj的评论

Ajax是异步的。当您的功能在底部运行时,您还没有完成呼叫。将“需要结果的代码”导入或调用到成功函数中。

$("#edit-field-order-borispol-und").change(function () {
    $.ajax({
        type: 'GET',
        url: '/ops',
        data: {
            'customerid': $(this).val()
        },
        success: function (response) {
            var result = response.borispol;
            alert(result + ' it works'); // cant make it to work..
            // insert code that depends on 'result'
            // either by copy/paste
            // or calling it:
            codeThatNeedsResult(result);
        }
    });
});

您还可以查看$ .ajax文档并考虑使用deferreds