Web サービス呼び出しから読み取った xml を使用してページに html を作成するために使用される jQuery プラグインを作成しました。バックアップとして、webservice 呼び出しが失敗した場合、html の構築に使用するデフォルトの xml が var に格納されています。現在、Web サービスを利用できないため、ダミーの xml を使用して障害シナリオをテストしています。$.ajax 呼び出しを除外してすべてを記述し、作業しています。コードに Web サービスへの $.ajax 呼び出しを含めても問題なく動作しますが、チェーンは壊れています。
私は "return this;" を知っています. $.when().then() を実装して $.ajax 呼び出しをラップし、ajax 呼び出しの非同期の性質がもたらす可能性のある問題に対処しましたが、連鎖は依然として行われます。うまくいかない。firebug コンソールは、チェーン内の次のメソッドに到達すると、メソッドの戻り値が定義されていないことを常に通知します。私のコードは以下のとおりです(時間を節約するために多くを疑似コードに置き換えました):
(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 );