0

我创建了一个 jQuery 插件,用于在页面上创建带有从 web 服务调用中读取的 xml 的 html。作为备份,如果 web 服务调用失败,则默认 xml 存储在 var 中以用于构建 html。现在,我无法使用 Web 服务,所以我只能使用虚拟 xml 测试失败场景。我已经编写了所有内容并使用了 $.ajax 调用,当我在我的代码中包含对 web 服务的 $.ajax 调用时,它仍然可以正常工作,但是链接被破坏了。

我知道要“返回这个;”,并且我已经实现了 $.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 );
4

1 回答 1

1

这是因为您是从回调函数返回的,而不是函数本身。当您的 AJAX 请求完成时,您的原始函数早已返回undefined

就在您的 AJAX 调用之后,就在函数结束之前,您可能想要return $this;

于 2012-06-12T20:13:21.870 回答