如何在$.ajax中覆盖jQuery对XMLHttpRequest的使用?
发布时间:2020-12-16 03:08:43 所属栏目:百科 来源:网络整理
导读:我需要addEventListener在打开XMLHttp连接之前侦听progress事件(即xhr.open()),但beforeSend方法返回已经打开的xhr实例.如何覆盖它以正确添加侦听器? (Note: You need to add the event listeners before calling open() on the request. Otherwise the pro
我需要addEventListener在打开XMLHttp连接之前侦听progress事件(即xhr.open()),但beforeSend方法返回已经打开的xhr实例.如何覆盖它以正确添加侦听器?
(Note: You need to add the event listeners before calling open() on the request. Otherwise the progress events will not fire.)
您可以在
ajaxSetup 中覆盖xhr函数,甚至可以覆盖每个$.ajax调用.这在
$.ajax 文档中有记录(感谢尼克!).
如果您想要始终执行此操作,您的代码可能看起来像这样(未经测试): (function() { var originalXhr = jQuery.ajaxSettings.xhr; jQuery.ajaxSetup({ xhr: function() { var req = originalXhr(); if (req) { // Add your progress handler } return req; } }); })(); …或像这样(live example)仅针对特定请求: $.ajax({ url: "path/to/resource",xhr: function() { var req = $.ajaxSettings.xhr(); if (req) { // Add your handler here } return req; } }); 不幸的是,尽管记录了覆盖xhr,但是当前配置的位置(jQuery.ajaxSettings.xhr)似乎并不存在,所以从技术上讲,你依旧使用jQuery.ajaxSettings.xhr来依赖于未记录的功能.码.你只需要仔细检查每个点发布时是否仍然存在,它可能不会过多地移动(并且jQuery.ajaxSettings至少在文档中提到,here). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |