2013-06-27 81 views
1

我有两个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); 
     } 
    }); 
}; 

当我打印出来的itemList中的Controller.js一切工作正常。 有什么建议吗?

+3

我不会建议使用synchronousJAX,但我认为你需要把'return itemList;'放在你的main函数的底部,而不是在'success'内相关: – Ian

+0

[如何从AJAX返回响应打电话?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) –

回答

2

您必须返回ParseXML函数末尾的值,而不是success函数的末尾。

​​
0

您可能想考虑让您的ajax调用异步并向您的ParseXML函数添加回调。像这样的事情在事件处理程序:

itemList = Controller.ParseXML("app/data/Event.xml", function(itemList){ 
    alert("itemList = " + itemList); 
}); 

而且在ParseXML:

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

$.ajax({ 
    type: "GET", 
    url: url, 
    dataType: "xml", 
    async: true, 
    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 
      }; 
      callback(itemList); 
     }); 
    }, 
    error: function(xhr, ajaxOptions, thrownError){ 
     alert("XML ERROR"); 
     alert(xhr.status); 
     alert(thrownError); 
     callback("XML ERROR " + xhr.status + " " + thrownError); 
    } 
}); 

};

你会想检查回调中的错误当然是错误的。