XMLHttpRequest()有时可以工作而有些则无效

时间:2018-02-15 05:41:47

标签: javascript jquery ajax xmlhttprequest

我有一个函数来做XMLHttpRequest()并随机在Chrome和IE中工作。该功能由On-click触发。试图捕获错误唯一可以获得的是readystate = 4但由于浏览器拒绝而status = 0。我会感激一些帮助。如果我在req.send之后包含最后一个alert(),那么在IE中工作得更好。 这是我的功能:

<script type="text/javascript">
function getPDF(Inv, agent, ddId, meth, url){
        var invoice = Invoiceid + ".pdf";
        console.log("Start");
        var req = new XMLHttpRequest();
        console.log("opened");
        if ("withCredentials" in req) {
          // req for Chrome/Firefox/Opera/Safari.
           req.open(meth, url, true);
        } else if (typeof XDomainRequest != "undefined") {
         // XDomainRequest for IE.
           req = new XDomainRequest();
           req.open(meth, url);
        } else {
          // CORS not supported.
          req = null;
        }
        req.setRequestHeader("Content-type", "application/json");
        req.setRequestHeader("AGENT", agent);
        req.responseType = "blob";
        req.onload = function (event) {
            var data = event.target.response;
            console.log(req.response);
                var blob = new Blob([data]);
                if (window.navigator.msSaveOrOpenBlob)  // IF IE or Edge
                    window.navigator.msSaveOrOpenBlob(blob,invoice);
                else                                   // All Other Browsers
                {
                    var a = window.document.createElement("a");
                    a.href = window.URL.createObjectURL(blob, {type: "application/pdf"});
                    a.download = invoice ;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);  
                }
        };

        req.onreadystatechange = function (event) {

            if (req.readyState === 4) {  
                if (req.status === 200) {  
                  alert("Open or Save the downloaded file : " + invoice);
                } else {  
                  console.log(req.status);  
                }  
            }  
        }; 
        req.onerror = function (event) {
          console.log("** An error occurred during the transaction");
        };

        req.send(null);
        alert(1); // 

  }
</script>

1 个答案:

答案 0 :(得分:-1)

我很确定问题出在CORS标题上。不幸的是,我只是从客户端开发并在外部对服务器端进行故障排除。我做了什么来解决这个问题,我只是在我的http请求中包含了一个额外的标题。 :setRequestHeader(&#34; Access-Control-Allow-Origin&#34;,&#34; 8&#34;)。