onReadyStateChange not firing in IE for XHR Reques

2020-05-03 12:13发布

问题:

I have this code that I am using and it works fine in chrome, but in IE, it looks like that onreadystatechenge is not firing.

How do I get this to work cross browser. I read that in IE you have to place the onreadystatechange event before the send, But that didn't work.

The alert here is not firing. And yes it is successful.

if (xhr.status==200 && xhr.readyState==4)
    {
        alert("DONE!");
    }

This is the entire request.

function SendFile(evt)
{
var xhr = new XMLHttpRequest();
var data = new FormData();
var files = $("#FileUpload1").get(0).files;

for (var i = 0; i < files.length; i++)
{

    data.append(files[i].name, files[i]);
}
xhr.upload.addEventListener("progress", function (evt)
{
    if (evt.lengthComputable)
    {
        var progress = Math.round(evt.loaded * 100 / evt.total);
        $("#progressbar").progressbar("value", progress);
    }
}, false);
xhr.open("POST", "Handler.ashx");

xhr.onreadystatechange=function ()
{
    if (xhr.status==200 && xhr.readyState==4)
    {
        alert("DONE!");
    }
}
xhr.send(data);


$("#progressbar").progressbar({
    max: 100,
    change: function (evt, ui)
    {
        $("#progresslabel").text($("#progressbar").progressbar("value") + "%");
    },
    complete: function (evt, ui)
    {
        $("#progresslabel").text("File upload successful!");
        GetID();
    }
});

}

Tried onload with no luck.

   xhr.onload = function ()
    {
        if (xhr.readyState == 4 && xhr.status==200)
        {
            alert("IE DONE!");

        }
    }

回答1:

Your XMLHttpRequest object might be caching.

Try:

var myNoCachePage = document.location + '?' + new Date().getTime();
xhr.open("GET", myNoCachePage, true);  // Prevent IE11 from caching
xhr.send();


回答2:

Apparently IE 11 (which I assume is what you are testing is broken) removed script.onreadystatechange in favor of script.onload.

Here is the compatibility for xhr.onload.

Source of IE11 removing it