2012-06-12 1 views
0

webservice 호출에서 읽는 xml이있는 페이지에서 html을 만드는 데 사용되는 jQuery 플러그인을 만들었습니다. 백업으로 webservice 호출이 실패하면 var에 저장된 기본 xml이 html을 빌드하는 데 사용됩니다. 지금 당장 webservice를 사용할 수 없으므로 더미 XML을 사용하여 실패 시나리오를 테스트 할 수 있습니다. 내가 작성한 모든 $ .ajax 호출을 제외하고 작업, 내 코드에서 webservice에 $ .ajax 호출을 포함 시켰을 때 여전히 정상적으로 작동하지만 체인이 끊어집니다.

"return this;"나는 $ .wax()를 구현하여 $ .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); 
+1

당신이 AJAX 요청에서 값을 반환하려고하려는거야? 이것이 바로 AJAX가 작동하지 않는 방식이기 때문입니다. – Blazemonger

답변

1

. AJAX 요청이 완료 될 때까지 원래 함수는 undefined을 반환했습니다.

은 그냥 AJAX 호출 후에, 단지 기능이 끝나기 전에, 당신은 아마 return $this;

+0

고마워, 고쳐! 내가 AJAX를 잘못 사용하고있는 것 같습니다. – str8killinit