如何使用XMLHttpRequest在Firefox中返回文件?似乎从未达到readystate == 4和status == 200

时间:2018-12-28 15:39:20

标签: javascript jquery ajax xmlhttprequest

基本上,我正在使用Ajax调用C#WebMethod,该方法返回由Excel文件组成的字节数组。它可以在IE和Chrome中运行,但不能在Firefox中运行。控制台在FireFox中返回的readystate为4,但状态为0,而在其他浏览器中,控制台进入if块,其中readystate为4,状态为200。下面是代码。如果有人知道我做错了什么,我将非常感谢您提供的帮助,但是我尝试了一系列步骤来纠正这种情况,但没有一个工作。

如果我在包含alert('got here')的行之后插入xhttp.send,它将在Firefox中运行吗?

<script type="text/javascript">
    $("#operation").click(function () {
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "Default.aspx/GetText");
        xhttp.addEventListener("progress", function (e) {
            if (e.lengthComputable) {
                //alert("TOTAL:" + e.total + " LOADED:" + e.loaded);

                var percentComplete = Math.ceil((e.loaded / e.total) * 100);
                progressBar.max = e.total;
                progressBar.val(percentComplete);

                //console.log(percentComplete);
            }
        }, false);
        xhttp.responseType = 'blob';
        xhttp.setRequestHeader("Content-Type", "application/json");
        xhttp.onreadystatechange = function () {
            var a;
            //console.log(xhttp);
            if (xhttp.readyState === 4 && xhttp.status === 200) {
                var blob = xhttp.response;
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = "ItemMatrix.xlsx";
                document.body.appendChild(link);
                link.click();
            } else {
                console.log(xhttp);
            }
        };
        xhttp.send(JSON.stringify({ sender: 'Generate Excel', itemLIST: $('#MainContent_itemnumberlist').val(), includeIMAGES: $('#<%= IncludeImages.ClientID %>').is(':checked') }));
    });
</script>

0 个答案:

没有答案