Jquery 使用$.ajax调用中断链接的自定义插件

Jquery 使用$.ajax调用中断链接的自定义插件,jquery,jquery-plugins,jquery-chaining,Jquery,Jquery Plugins,Jquery Chaining,我创建了一个jQuery插件,用于在页面上创建html,其中包含从webservice调用读取的xml。作为备份,如果webservice调用失败,则会在var中存储默认xml以用于构建html。现在,webservice对我不可用,所以我一直在用伪xml测试失败场景。我已经排除了所有编写和使用$.ajax调用的内容,当我在代码中包含对webservice的$.ajax调用时,它仍然可以正常工作,但链接已经中断 我知道“returnthis;”,我已经实现了$.when().then()包装我的

我创建了一个jQuery插件,用于在页面上创建html,其中包含从webservice调用读取的xml。作为备份,如果webservice调用失败,则会在var中存储默认xml以用于构建html。现在,webservice对我不可用,所以我一直在用伪xml测试失败场景。我已经排除了所有编写和使用$.ajax调用的内容,当我在代码中包含对webservice的$.ajax调用时,它仍然可以正常工作,但链接已经中断

我知道“returnthis;”,我已经实现了$.when().then()包装我的$.ajax调用,以解决ajax调用的异步特性可能带来的任何问题,但是链接仍然不起作用。firebug控制台总是告诉我,当我的方法返回到链中的下一个方法时,它是未定义的,这使我相信我实际上根本没有返回“this”,即使在我看来它像我一样。我的代码如下(为了节省时间,用伪代码替换了很多代码):

(函数($){
$.fn.createHtmlFromWS=函数(选项){
var$this=$(this);
//函数将解析后的xml输出为附加到调用插件的jQuery对象的HTML
函数buildNav(dispXml){
//将xml作为自定义html附加到$this的逻辑如下
退还$this;
}
//Web服务调用失败时的回退xml
var failXml='earth';
//用于强制webservice失败场景的虚拟服务url
var serviceUrl=http://1234lkjasdf/test';
//注意:此调用不尝试$。对webservice的ajax调用使用链接
//返回buildNav($.parseXML(failXml));
//调用Web服务
$.when($.ajax({
键入:“GET”,
数据类型:“xml”,
url:serviceUrl,
超时时间:10,,
})).then(函数(a1){//如果成功,则调用函数
返回buildNav($.parseXML(a1[2].responseXml));
},function(){//失败时要调用的函数
console.log(“在then的错误部分”);//注意:这是对log的输出,我知道我在正确的位置
//这一行似乎没有返回链接所需的$then,尽管它正在按预期构建html
返回buildNav($.parseXML(failXml));
}); 
};
})(jQuery);

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


在AJAX调用之后,在函数结束之前,您可能希望
返回$this

是否尝试从AJAX请求中返回值?因为这正是AJAX不起作用的原因。谢谢,这就解决了它!看来我只是用错了AJAX。
(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 );