首页 > 解决方案 > ajax调用返回值问题

问题描述

我在使用 ajax 调用时遇到问题,我认为返回值没有正确返回。

我有一个加载 2 个 javascript 文件的 index.html 页面:

index.js

$(document).ready(function() {
    console.log(ApplicationModule.getEventById(123));  // undefined if I use return result[0];
})

应用程序.js

var ApplicationModule = (function () {
    // return "foo"; this works in index.html ("foo")
    function getEventById(id) {
        // ajax call returns a json object (list of {"title":"<the title>"} objects)
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            url: "/api/v1/eventtool/" + id,
            success: function (result) {
                console.log(result[0]);  // works fine -> {"title":"my title"}
                return result[0];  // does not work in index.html (undefined)
            }
        });
    }

    return {
        getEventById : getEventById
    };

})(ApplicationModule || {});

如果我取消注释 [ return "foo" ] 行,一切都会按预期工作,并且我会在控制台上看到 "foo"。如果我评论这一行以执行 ajax 调用,我会得到“未定义”。为什么?

我的ajax调用有问题吗?

标签: ajax

解决方案


返回值不起作用,您应该使用 DOM 指定一个元素,如下所示:$("#el").html(result[0]);


推荐阅读