开发者

how to return jquery ajax success result [duplicate]

开发者 https://www.devze.com 2023-04-03 18:31 出处:网络
This question already has answers here: How do I return the response from an asynchronous call? (41 answers)
This question already has answers here: How do I return the response from an asynchronous call? (41 answers) Closed 7 years ago.

how to return jquery ajax success result

function name (LevelId) {
    var passobj = null;
    $.ajax({
        url: 'GetValues' + '/?LevelId=' + LevelId,
        type: "POST",
        dataType: "json",
        contentType: 'application/json',
        async: false,
        success: function (result) {
            passobj = result;
        },
 开发者_开发百科       complete: function () { },
        error: ServiceFailed// When Service call fails
    });
    return passobj;
}

  returned =name(id);


This worked for me

ajaxCall(urls, data).success(function(data){
    // get the result
});

function ajaxCall(url, data){   
    var result;

    return $.ajax({
        type: 'POST',
        url: url,
        data: data
    });
}


That won't work, because the ajax request is performed asynchronous what means that your function returns null - the success event handler is not called until the response from the server is retrieved (what may take some time). You will need to refactor your code using events.

function name(id, callback) {
    $.ajax({
        ...
        success: callback
    });
}

name(17, function(returned) {
    // work with the response...
});

EDIT: Sorry, didn't notice that you set async: false - in that case your code is actually supposed to be working fine, if I don't miss anything again.

0

精彩评论

暂无评论...
验证码 换一张
取 消