【问题标题】:AJAX code fails on Firefox and IE11 but ok on Chrome and OperaAJAX 代码在 Firefox 和 IE11 上失败,但在 Chrome 和 Opera 上正常
【发布时间】:2016-07-12 16:57:50
【问题描述】:

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

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

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

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

通过在网络上使用 Wireshark,我可以看到 Chrome 和 Opera 始终为“clientes.xml”文件发送 HTTP GET 消息,但在 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>

【问题讨论】:

    标签: ajax firefox


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      相关资源
      最近更新 更多