javascript 保存来自 jQuery ajax 函数的响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8077443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:10:34  来源:igfitidea点击:

Save response from jQuery ajax function

javascriptajaxjquery

提问by Peter O.

I've got a custom function, which calls ajax request and I'm able to save response data to variable and return it. 0is always returned, but alert shows e.g. 3712.

我有一个自定义函数,它调用 ajax 请求,我能够将响应数据保存到变量并返回它。0总是返回,但警报显示例如 3712。

Here is the function:

这是函数:

function getNo(index, val) {

var $ret = 0;

$('body').showLoading();
$.ajax({
    type: 'POST',
    url: BASE_URL + 'tools/no.php?id='+index+'&value='+val,
    data: $("#form").serialize(),
    cache: false,
    success: function(data) {
        $('body').hideLoading();
        alert('data: ' + data);
        $ret = data;
    }
});
return $ret;
}

回答by James.Xu

because ajaxis asynchronous, when return $ret;is executed, the response is not ready yet, so its initial value 0is returned.

因为ajax异步的return $ret;执行时,响应还没有准备好,所以0返回它的初始值。

you have to do what you want to do in the successcallback function rather than return.

你必须在success回调函数中做你想做的事情而不是返回。

回答by Abdul Munim

This will return ZERObecause of the asynchronous call. Rather I would suggest you to pass a callback method to work with the response.

由于异步调用,这将返回。相反,我建议您传递一个回调方法来处理响应。

See an example below:

请参阅下面的示例:

function getNo(index, val, callback) {
    var $ret = 0;

    $('body').showLoading();
    $.ajax({
        type: 'POST',
        url: BASE_URL + 'tools/no.php?id=' + index + '&value=' + val,
        data: $("#form").serialize(),
        cache: false,
        success: function (data) {
            $('body').hideLoading();
            callback(data);
        }
    });
    return $ret;
}

//USAGE
getNo(3, "value", function (data) {
    //do something with data responded from the server
    alert(data);
});

回答by Moe Sweet

Because "A" in Ajax stands for Asynchronous, return $ret;is executed before the Ajax call finds it's way back to success function.

因为 Ajax 中的“A”代表异步,return $ret;在 Ajax 调用找到返回成功函数之前执行。

Rather than trying to return the value, try to call a function within the ajax success block.

与其尝试返回值,不如尝试在 ajax 成功块中调用函数。

success: function(data) {
    $('body').hideLoading();
    alert('data: ' + data);
    $ret = data;
doSomething(data);
}