我已經創建了一個jQuery插件,用於使用它從webservice調用中讀取的xml在頁面上創建html。作爲備份,如果Web服務調用失敗,則存儲在var中的默認xml用於構建html。現在,Web服務對我來說是不可用的,所以我被困在用虛擬XML測試失敗的場景。我將所有編寫和使用$ .ajax調用的東西都排除在外,當我在代碼中將$ .ajax調用包含到web服務中時,它仍然可以正常工作,但是鏈接已斷開。我知道要「返回這個」,並且我實現了$ .when()。then()包裝我的$ .ajax調用來處理任何可能引入ajax調用的異步性質的問題,但鏈接仍然不起作用。螢火蟲控制檯總是告訴我,當它到達鏈中的下一個方法時,我的方法返回值是不確定的,這導致我相信我實際上並沒有返回「this」,即使它看起來像我一樣。我的代碼如下(取代了很多與僞代碼,以節省時間):
(function($) {
$.fn.createHtmlFromWS = function(options) {
var $this = $(this);
//function to output the parsed xml as HTML appended to the jQuery object the plugin was called on
function buildNav(dispXml){
//logic to append xml to $this as custom html goes here
return $this;
}
//fallback xml if webservice call fails
var failXml = '<?xml version="1.0" encoding="utf-8"?><hello><world>earth</world></hello>';
//dummy service url to force webservice fail scenario
var serviceUrl = 'http://1234lkjasdf/test';
//Note: this call that does not attempt $.ajax call to webservice WORKS with chaining
//return buildNav($.parseXML(failXml));
//call to webservice
$.when($.ajax({
type: 'GET',
dataType: 'xml',
url: serviceUrl,
timeout: 10,
})).then(function(a1) { //function to call if succeeded
return buildNav($.parseXML(a1[2].responseXml));
}, function(){ //function to call if failed
console.log("in the error part of then"); //Note: this is output to log, I know i'm in the right spot
//This line does not seem to be returning $then which is required for chaining, although it is building the html as expected
return buildNav($.parseXML(failXml));
});
};
}) (jQuery);
你試圖返回一個值了一個AJAX請求的?因爲這正是AJAX如何不起作用。 – Blazemonger