javascript - 返回不返回对象

标签 javascript jquery samsung-smart-tv

我有两个 javascript 类(Controller.js 和 Events.js)。 我从 Events.js 调用 Controller.js 中的 XML 解析器。解析器工作但不返回任何内容:

SceneEvent.prototype.handleKeyDown = function (keyCode) {
    switch (keyCode) {
        case sf.key.ENTER:
            var itemList = null;    
            itemList = Controller.ParseXML("app/data/Event.xml");   
            alert("itemList = " + itemList);
    }
};

Controller.js 看起来像这样:

Controller.ParseXML = function (url) {
    var itemList = null;

    $.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        async: false,
        success: function(xml) {
            $(xml).find("event").each(function() {
                var _id = $(this).attr("id");
                var _eventItemDay = $(this).find("eventItemDay").text();
                ...
                var _eventItemLocation = $(this).find("eventItemLocation").text();

                itemList = {
                    id: _id,
                    eventItemDay: _eventItemDay,
                    eventItemLocation: _eventItemLocation,
                    ...
                    eventItemLocation: _eventItemLocation
                };
            });
            return itemList;
        },
        error: function(xhr, ajaxOptions, thrownError){
            alert("XML ERROR");
            alert(xhr.status);
            alert(thrownError);
        }
    });
};

当我在 Controller.js 中打印出 itemList 时,一切正常。 有什么建议吗?

最佳答案

您必须在 ParseXML 函数结束时返回值,而不是在 success 函数结束时返回值。

Controller.ParseXML = function (url) {
    var itemList = null;

    $.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        async: false,
        success: function(xml) {
            $(xml).find("event").each(function() {
                var _id = $(this).attr("id");
                var _eventItemDay = $(this).find("eventItemDay").text();
                ...
                var _eventItemLocation = $(this).find("eventItemLocation").text();

                itemList = {
                    id: _id,
                    eventItemDay: _eventItemDay,
                    eventItemLocation: _eventItemLocation,
                    ...
                    eventItemLocation: _eventItemLocation
                };
            });

        },
        error: function(xhr, ajaxOptions, thrownError){
            alert("XML ERROR");
            alert(xhr.status);
            alert(thrownError);
        }
    });

    return itemList;
};

关于javascript - 返回不返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17346004/

相关文章:

jquery - 占位符和 ie9

javascript - 三星智能电视如何清除应用程序缓存

javascript - 如何在退出当前 Tizen 应用程序时启动先前的 Tizen 应用程序?

javascript - Texturise 文本支持 Firefox , Chrome

javascript - 创建一个没有重复项的多维对象数组

javascript - 当所有动态图像完成加载时,jquery 发出警报

javascript - jquery 对象属性值平均值

javascript - Smart Tv 应用程序(css 和 Javascript)- 如何循环显示视频流和循环登录

javascript - HTML - 如何在固定上下文中的移动设备上拖放

javascript - Firefox 无法读取获取响应 header