2013-06-27 327 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); 
    } 
}); 

};

你會想檢查回調中的錯誤當然是錯誤的。