2014-10-01 76 views
1

我刚刚移动到jquery 1.11.1(我在1.2.x之前在这个项目上)。用于将响应文本/ html拉入元素的$ .load函数似乎并没有突然触发回调!Jquery加载回调不启动时,实际加载的东西

$("#thing").load("page", null, callback); 

所以我调试了jQuery代码..如预期它使用$阿贾克斯,抓住一个页面,它PULS使用$ html的自我,然后回调实际上是对的“完整”的功能解雇$就。无论ajax是否成功,此功能都会始终开启。驾驶自己INSANE一段时间后,我试图只是调用调用自己来测试我是不是真的要疯了..这是我发现

$.ajax({url:"page"}) 
      .done(function(r){ 
       $("#thing").html(r); 
      }) 
      .complete(function(){alert("complete");}); 

这个填充元素,但并没有给我alernt ..但是下面的确让我警觉!为什么?

$.ajax({url:"page"}) 
      .done(function(r){ 
       //$("#thing").html(r); 
       alert("done...?"); 
      }) 
      .complete(function(){alert("complete");}); 

我同时获得完成和完整警报..

更新1

有关使用 “总是”,而不是 “完整” 的评论。我想用“负荷”而不是“AJAX”的,这是JQ代码1.11.1

// Keep a copy of the old load method 
var _load = jQuery.fn.load; 

/** 
* Load a url into a page 
*/ 
jQuery.fn.load = function(url, params, callback) { 
    if (typeof url !== "string" && _load) { 
     return _load.apply(this, arguments); 
    } 

    var selector, response, type, 
     self = this, 
     off = url.indexOf(" "); 

    if (off >= 0) { 
     selector = jQuery.trim(url.slice(off, url.length)); 
     url = url.slice(0, off); 
    } 

    // If it's a function 
    if (jQuery.isFunction(params)) { 

     // We assume that it's the callback 
     callback = params; 
     params = undefined; 

    // Otherwise, build a param string 
    } else if (params && typeof params === "object") { 
     type = "POST"; 
    } 

    // If we have elements to modify, make the request 
    if (self.length > 0) { 
     jQuery.ajax({ 
      url: url, 

      // if "type" variable is undefined, then "GET" method will be used 
      type: type, 
      dataType: "html", 
      data: params 
     }).done(function(responseText) { 

      // Save response for use in complete callback 
      response = arguments; 

      self.html(selector ? 

       // If a selector was specified, locate the right elements in a dummy div 
       // Exclude scripts to avoid IE 'Permission Denied' errors 
       jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) : 

       // Otherwise use the full result 
       responseText); 

     }).complete(callback && function(jqXHR, status) { 
      self.each(callback, response || [ jqXHR.responseText, status, jqXHR ]); 
     }); 
    } 
    return this; 
}; 

通知它如何使用“完整” ..

+1

'.complete'在1.11中不存在,它是'.always'。你的第一个例子虽然应该工作。删除'空',' – 2014-10-01 16:12:55

+0

这不是我所做的..这就是实际的jquery“加载”方法.. ..我无法控制这个 – 2014-10-01 16:17:19

+0

我...不理解你的评论。 – 2014-10-01 16:17:52

回答

1

这里的问题是一个奇怪的一个。从我的页面返回的HTML无效!尽管它足以显示。在“load”方法内部,在responseText/html的附加处调用$ .parseHTML方法。这会抛出并返回html,你会看到在目标元素中填充的html。

它应该可能做的就是捕获这个异常并忽略它,这样每次都会调用“complete”方法(所以我把它看作是jquery中的一个bug)。

+0

如果只有jQuery的承诺系统更像是本地的,那么你可以使用.Catch。> 。< – 2014-10-01 16:36:37

+0

是否需要在调用'.load()'返回的'html'中捕获错误? – guest271314 2014-10-01 16:39:59

+0

我想你可以使用$ patch的.parseHTML来捕获和忽略任何引起的错误,但是你永远不会知道如果你有无效的html。 – 2014-10-01 16:41:52