开发者

Javascript for..in and jQuery's $.for() don't work for XMLHttpRequest in IE

开发者 https://www.devze.com 2022-12-20 10:01 出处:网络
UPDATE:The problem only occurs when I use an older version of jQuery (1.3.2) and not on the newest version (1.4.2).

UPDATE: The problem only occurs when I use an older version of jQuery (1.3.2) and not on the newest version (1.4.2).

ORIGINAL QUESTION:

I have found a weird behavior, and am wondering if there are any work-arounds. The javascript 'for' loop can be used to enumerate the property names of an object. I am finding though that on IE it does not work for some objects, particularly an XMLHttpRequest. Consider the following code. It will open an alert box for every property on the XMLHttpRequest on Firefox. On IE however, no properties are found. If I step through with the debugger, there are definitely properties on the object. If I use jQuery's $.for() function, I see the same result.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
      "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

    <script src="http://code.jquery.com/jquery-latest.js"></script>

    <script>
        $(document).ready(function() {

            $.ajax({
                url: "/willneverwork/",
                timeout: 1,
                error: function(xmlHttpRequest) {

                    for (key in xmlHttpRequest) {
                        alert(key);
                    }
                }
            });
开发者_运维百科        });
    </script>

</head>
<body>
</body>
</html>


In jQuery 1.3.2, the ajax methods create the XMLHttpRequest using the following code:

return window.ActiveXObject 
           ? new ActiveXObject("Microsoft.XMLHTTP") 
           : new XMLHttpRequest();

This means that in IE7 and IE8, instead of the native XMLHttpRequest object being instantiated, the ActiveX equivalent, Microsoft.XMLHTTP, is instantiated instead. The short answer is that properties and methods of ActiveX controls aren't enumerable, hence for...in will not discover anything.

0

精彩评论

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

关注公众号