Is it possible for an AJAX request to be read before the response is complete?
I have an ajax req开发者_运维知识库uest that takes a while to complete, but the server does output some content along the way. If I load the request simply in the browser, I can see the page slowly loading and it can be stopped at any time. Is it possible to access an incomplete ajax request before the server closes the response?
The way to accomplish this is by listening on the readyState in the the xhr object. When readyState == 3 it means new content has arrived and you can access it. The technique is referred to as Comet.
Note however that different browsers behave differently here, IE will not allow you to access it See Here and webkit browsers (Chrome/Safari) buffer 2KB of data before making it available. After accounting for that though, you can then listen for the change then act on it.
Unfortunately, jQuery does not currently support this out of the box. You can get around this as noted in Bug #8327, where they basically fall back to polling on the readyState to see if it changes. They have plans to maybe do something about it in the future, Bug #9883, but don't hold your breath.
So finally, yes it is possible, no it is not easy.
There are some good answers already, but none of them are really 100% reliable or cross-browser. A safer approach would probably be to chunk your response into "pages". Each request can specify something equivalent to a LIMIT
and OFFSET
and you keep making requests until you get an empty response. That incurs some extra overhead on both the client and server, but it would be more robust.
Taken from: https://stackoverflow.com/questions/287286/jquery-is-req-readystate- 3-possible
Assign your ajax call to a variable and attach an event to its readystatechanged
.
var xhr = $.ajax(...);
xhr._onreadystatechange = xhr.onreadystatechange;
xhr.onreadystatechange = function() {
xhr._onreadystatechange();
if (xhr.readyState == 3) alert('Interactive');
};
I don't know for sure if this will work but it's worth a try:
$.ajax({
statusCode: {
206: function() { // 206 is partial content
// do work
}
}
});
Can you use long polling (comet) instead of ajax? Then you can flush the output buffers and read the content as the request is being processed.
http://www.zeitoun.net/articles/comet_and_php/start
Comet is a nice workaround right now, but it will be replaced by WebSockets in the near future.
Of course, WebSockets aren't supported out-of-the-box with many common web browsers yet, but there are already a number of polyfills that mimic the functionality in dull-edged browsers, many of which rely on Comet (XHR long polling) under the hood to mimic the functionality.
Personally, I prefer the socket.io polyfill, but my experience with it is limited to use alongside node.js, which may or may not mesh well with what you're working with.
精彩评论