ajax 函数返回值 undefined / [object object] for jquery v3.41+

Mec*_*ech -4 ajax jquery return return-value

在我的研究中,我一直无法找到不包含折旧的 jquery 功能的 ajax 函数示例。我需要 v3.4.1 / 2020 解决方案。


问题:

我可以获得将数据正确输出到console.log()a 之前的函数return。我的期望是console.log()显示返回的数据。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
function getData (url, privateToken) {
    $.ajax({
        'crossDomain': true,
        'url': url,
        'method': 'GET',
        'headers': {
            'PRIVATE-TOKEN': privateToken
        }
    })
    .done(function (response) {

        console.log(response[0].id);  // works correctly

        // ===================================

        var test = response[0].id;    
        console.log(test);            // works correctly

        // ===================================

        return response;              // does not work, `[object object]`` when function is called

        // ===================================

        return response[0].id;        // does not work, `undefined` when function is called

        // ===================================

        var test = response[0].id;    
        return test;                  // does not work, `undefined` when function is called

        // ===================================

        var test = response;    
        return test;                  // does not work, `[object object]` when function is called

        // ===================================

        return $(response).id;        // does not work, `undefined` when function is called
    });
}

$(document).ready(function(){
    console.log(getData("https://example.com/rest/api/xyz", "<private token>"));
});
Run Code Online (Sandbox Code Playgroud)

请注意,我知道代码将在第一个return. 我只是想以易于理解的方式展示所尝试的内容。

Don*_*nic 5

正如评论中所指出的,这与现代 jQuery 代码或约定无关,而更多是对从异步 jQuery 调用返回数据的误解。新代码或旧代码,您无法从 adone()always()callback返回响应。

jQuery 文档本身包含一个简单的示例 - 在The jqXHR Object 下,向下滚动黄色Deprecation Notice下方。

这是一个使用 jQuery 文档中描述的方法修改后的代码版本的有效 JSFiddle。在控制台打开的情况下查看它,我添加了一系列console.log()s 来显示运行的顺序,并演示按预期获取和使用响应。请注意,JSFiddle 包含一种通过将异步请求发送到 来模拟异步请求的方法/echo/json,我已经更新了代码以使用它,以便我们可以看到它的工作情况。

function getData (url, privateToken) {
    // return the jqXHR object, which is not your response!
    return $.ajax({
        'url': url,
        // ... etc
    }).done(function (response) {
        // you can log response here, display alerts, manipulate DOM, etc,
        // but not return anything useful
    });
}

$(document).ready(function(){
    var $ajax = getData("/echo/json/", "token");
    // Execution will continue here long before getData has completed
    $ajax.always(function(response, textStatus, jqXHR) {
        // Now getData has finished, and we have the response!
        console.dir(response);
    });
});
Run Code Online (Sandbox Code Playgroud)