readyState event for HEADERS_RECEIVED using jQuery.ajax
readyState event for HEADERS_RECEIVED using jQuery.ajax
使用本机XMLHttpRequest
对象,可以将事件侦听器添加到onreadystatechange
事件,并在readyState
2
或HEADERS_RECEIVED
时收到通知。这很有用,因为这可以在长传输完成之前读取 HTTP 响应标头。
然而,在jQuery的AJAX包装器中,似乎没有任何方法可以做到这一点。jQuery.ajax API文档实际上说了以下内容。
然而,没有提供
onreadystatechange
机制,因为done
、fail
、always
和statusCode
涵盖了所有可以想象的需求。
除非我弄错了,否则所有列出的回调都是在收到整个请求后触发的,这可能是标头可用并且readyState
2
后的很长时间。
有没有办法在使用 jQuery 的 AJAX 包装器时向onreadystatechange
和/或readyState
2
添加回调,而无需轮询 readyState
属性?
我想可以使用setInterval
轮询 AJAX 对象的 readyState
属性,但由于显而易见的原因,我认为这不是一个真正的解决方案。我也不认为修改jQuery的核心是一个真正的解决方案。
更新:
另一位SO用户将我引导到这个问题。不幸的是,这些答案似乎都不起作用。修改jQuery不是一个真正的解决方案。使用 jQuery 创建 XHR 对象类型违背了目的。最后一个答案根本行不通。事实上,整个问题看起来都是针对过时的jQuery。
好吧,简短的回答是,由于旧版浏览器中的兼容性问题,jQuery不提供此功能。为了解决这些问题,jQuery只是将标准降低到最低公分母。
稍长的答案是可以使用beforeSend
和xhr
方法将其修补到其中,但这并非微不足道,尤其是当您考虑到传统和跨浏览器兼容性时。为了减轻痛苦,我创建了一个jQuery插件来做到这一点。
这似乎是可能的。从 jQuery 获取XMLHttpRequest
对象,然后监视状态更改,如下所述:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
文档中的示例代码:
xhr.onreadystatechange = function () {
// In local files, status is 0 upon success in Mozilla Firefox
if(xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
// The request has been completed successfully
console.log(xhr.responseText);
} else {
// Oh no! There has been an error with the request!
}
}
};
- Using jQuery with classes from ES6
- Javascript Object - using jQuery and this
- focus Using Jquery <tr> <td>
- filtet data by checkbox using jquery ajax mysql and php
- Smooth requestAnimationFrame using Jquery.animate?
- readyState event for HEADERS_RECEIVED using jQuery.ajax
- Javascript Scope using JQuery
- Rest api get call using jquery
- Using jQuery LazyLoad for image grid with AngularJS SPA
- Using JQuery, AJAX and PHP
- HTML with XML using jQuery
- Using jQuery's serializeArray with Rails forms
- Using jQuery with Aurelia
- Using jQuery .when .then
- Using jQuery in Cloud9
- Songkick API Using JQuery
- incremental number using jQuery .each()
- Using jQuery noConflict() with script.aculo.us
- Using Jquery Ajax with PHP
- Using jQuery's animate with css filter.