【问题标题】:Custom plugin using $.ajax call breaks chaining使用 $.ajax 调用中断链接的自定义插件
【发布时间】:2012-06-12 20:06:07
【问题描述】:

我创建了一个 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 );

【问题讨论】:

  • 您是否试图从 AJAX 请求中返回一个值?因为这正是 AJAX 不起作用的原因。

标签: jquery jquery-plugins jquery-chaining


【解决方案1】:

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

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

【讨论】:

  • 谢谢,解决了!似乎我只是以错误的方式使用 AJAX。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多