开发者

AJAX fires readyState 4 multiple times in IE

开发者 https://www.devze.com 2023-03-13 18:29 出处:网络
I am experiencing a strange problem where IE8 will fire readyState 4 three or four times on an ajax request.This happens often but not always, and only for a couple of specific links - the rest of my

I am experiencing a strange problem where IE8 will fire readyState 4 three or four times on an ajax request. This happens often but not always, and only for a couple of specific links - the rest of my ajax links are fine. My object creation and onreadystatechange handler are basic, ie.

function ajaxPost(params) {

    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert('Unsupported Browser');
            }
        }
    }

    xmlHttp.onreadystatechange = function() {
      开发者_运维知识库  if (xmlHttp.readyState == 4) {
            // Do something
        }
    }

    xmlHttp.open("POST", path_to_script);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    xmlHttp.setRequestHeader("Cache-Control", "must-revalidate");
    xmlHttp.send(params);
}

Not sure if this is relevant - but at the points where the problem happens the user has already been navigating an ajax UI. They have clicked several other ajax links without reloading the page - each link uses a new xmlHttpRequest object with the same global variable name (xmlHttp), but each ajax request finishes before another can be issued. Do I need to do any "cleanup" or something for IE8? This has never happened using Safari, Firefox, Chrome, or any other browser.

Any insight would be much appreciated.

Thanks, Brian


Since your xmlHttp object is global, may be IE8 assigns a new onreadystatechange each time you call ajaxPost instead of replacing it.

That may explain an erratic behavior, as it depends on the number of calls to ajaxPost.


I'm wondering if you're having the same problem I had.

Is it possible that the onreadystatechange functions aren't getting executed immediately?

The ready state changes 3 times (1 to 2, 2 to 3, and 3 to 4), but if execution gets delayed, when the functions DO execute, they'll see the current ready state of 4. Because there are 3 readychange events, and they all see readystate = 4, they all execute.

0

精彩评论

暂无评论...
验证码 换一张
取 消