简体   繁体   中英

Long Polling - Problems with Internet Explorer 8

I'm trying to implement long polling using Netty and jQuery.

I have it working correctly with Chrome and Firefox, but Internet Explorer 8 is causing me problems.

I'm executing the following code which sends a request to my server, waits until a response is received from the server and then sends another request.

function longPollRequest() {
    $.ajax({
        url: '/test-path',
        type: 'GET',
        success: function(data, textStatus, jqXHR) {
            longPollRequest();
            console.log('Received: ' + data);
        }
    });
}

However, in IE8 I'm running into an infinite loop, which is freezing the browser. The interesting part is that my server is only receiving the first request from IE. I'm really puzzled as to what is going on. If anyone has any ideas I would really appreciate the help.

Disable caching and see if that fixes your issue:

function longPollRequest () {
    $.ajax({
        url     : '/test-path',
        type    : 'GET',
        cache   : false,
        success : function(data, textStatus, jqXHR) {
            longPollRequest();
            console.log('Received: ' + data);
        }
    });
}

This will force jQuery to append a time-stamp to each request. If the response is cached then it will return very quickly and there's a good chance that's what's causing your infinite loop.

You could also force a minimum delay between AJAX requests:

var lastRequestTime = 0;
function longPollRequest () {
    $.ajax({
        url     : '/test-path',
        type    : 'GET',
        cache   : false,
        success : function(data, textStatus, jqXHR) {
            var delay = ((new Date().getTime()) - lastRequestTime);
            if (delay > 1000) {
                delay = 0;
            } else {
                delay = (1000 - delay);
            }
            setTimeout(longPollRequest, delay);
            console.log('Received: ' + data);
        }
    });
}

This checks the current time against the time of the last AJAX request. If it's more than one second then just run the function again without a delay, otherwise make the code wait until a second has gone by between requests. There is probably a more elegant way of defining the delay variable but the above code should get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM