Firefox和IE11上的AJAX代码失败,但在Chrome和Opera上却没问题

时间:2016-03-24 23:01:02

标签: ajax firefox

我正在学习AJAX,我遇到以下代码的问题。 这是一个HTML页面,当下载到浏览器时,将允许用户按下按钮以检索' clientes.xml'来自服务器的文件。 代码看起来很简单,似乎符合AJAX理论。

如果我使用Chrome或Opera浏览器,它实际上可以正常工作。

问题是它总是在Firefox(v45)和IE11上失败。

通过使用浏览器控制台,会报告以下错误: Firefox:脚本的最后一行出现NS_ERROR_FAILURE错误:xhttp.send(); IE11:'权限被拒绝'同一脚本行上的错误:xhttp.send();

通过在网络上使用Wireshark,我可以看到始终为' clientes.xml'发送HTTP GET消息。使用Chrome和Opera文件,但Firefox或IE11不会发生这种情况。

我已经为此找到了可能的解释,但没有找到。

有谁知道Firefox和IE可能存在什么问题?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<script>
 var xhttp=new XMLHttpRequest();

 function doStuff(response) {
    // var papeis=response;
    var clientes=response.getElementsByTagName("nome");
    for (i = 0; i < clientes.length; i++) {
        document.write("<p>"); 
        document.write(clientes[i].childNodes[0].textContent);
    }
}

 function sendRequest() {
 var xhttp=new XMLHttpRequest();
   if (!xhttp) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    xhttp.onreadystatechange = function() {
    console.log (xhttp.readyState);
        if (xhttp.readyState!=4) {document.write("Not Yet Done: " + xhttp.readyState + "<br>" );}
        else if(xhttp.readyState===4 && xhttp.status===200) {
            doStuff(xhttp.responseXML);
        }
    }
    xhttp.open('GET','clientes.xml', true);
    xhttp.send();
 } 
</script>

</head>
<body>
<h3> AJAX </h3> <br>

<button onclick="sendRequest()">Click me</button>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

我发现问题出在哪里。问题出在我用于测试目的的javascript document.write()函数中。 如果我在sendRequest()函数中使用console.log()替换此函数,Firefox的行为方式与Chrome和Opera相同。