本文介绍了如何覆盖$阿​​贾克斯jQuery的使用XMLHtt prequest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要的addEventListener 来听进度事件 开场中的XMLHTTP连接之前(即 xhr.open()),但 beforeSend 方法返回一个XHR实例已经打开。我怎么会覆盖到适当加听众?

I need to addEventListener to listen for progress event before opening the XMLHttp connection (i.e. xhr.open()), but the beforeSend method returns an xhr instance already opened. How would I override it to add the listener properly?

注意:您需要调用open(前添加事件监听器)的要求,否则进度的事件​​将不会触发。

推荐答案

您可以覆盖 XHR 中的,甚至在每个单独的 $。阿贾克斯调用。这是记录在 $。阿贾克斯 文档的(感谢尼克!)的。

You can override the xhr function in ajaxSetup or even on each individual $.ajax call. This is documented in the $.ajax docs (thanks Nick!).

您code可能是这样的(未经测试)如果你想这样做的所有的时间:

Your code might look like this (untested) if you want to do this all the time:

(function() {
    var originalXhr = jQuery.ajaxSettings.xhr;
    jQuery.ajaxSetup({
        xhr: function() {
            var req = originalXhr();
            if (req) {
                // Add your progress handler
            }
            return req;
        }
    });
})();

...或者是这样的(活生生的例子)只是特定请求:

$.ajax({
  url: "path/to/resource",
  xhr: function() {
    var req = $.ajaxSettings.xhr();
    if (req) {
      // Add your handler here
    }
    return req;
  }
});

不幸的是,虽然覆盖 XHR 被记录,当前配置一(位置<$ C C $> jQuery.ajaxSettings.xhr )似乎没有要,所以理论上讲你仍然通过在code。使用 jQuery.ajaxSettings.xhr 依托无证功能。你只需要仔细检查这仍然存在于每一个点的释放,它可能不会走动太多(和 jQuery.ajaxSettings 至少的在文档,这里)。

Unfortunately, although overriding xhr is documented, the location of the currently-configured one (jQuery.ajaxSettings.xhr) doesn't seem to be, so technically you're still relying on an undocumented feature by using jQuery.ajaxSettings.xhr in your code. You just need to double-check that that's still there on each dot release, it's probably not going to move around too much (and jQuery.ajaxSettings is at least mentioned in the docs, here).

这篇关于如何覆盖$阿​​贾克斯jQuery的使用XMLHtt prequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:55