繁体   English   中英

尝试从服务器返回.txt时发生Javascript网络错误

[英]Javascript network error occurs when trying to return .txt from server

我的.html中有一个空div( id="theDiv" ),我正在尝试填充文本文件的内容。 它看起来像这样:

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="Practice.js"></script>
</head>
<body onload="process()">
    <p>Connected to server.</p>
    <div id="theDiv"></div>
</body>
</html>

我正在尝试打印出每个readyState在进程中发生的时间。 javascript看起来不错,但是当我运行页面时,我收到“NetworkError:发生网络错误”的警报。 我假设可能是由脚本中的第一个警报触发的。 我使用过linter但仍然不知道.js中的问题是什么,所以我会把所有东西放在这里:

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject() {
    var xmlHttp;

    if(window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }else{
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

return xmlHttp;
}

function process() {
    if(xmlHttp) {
      try{
        xmlHttp.open("GET", "Practice.txt", true);
        xmlHttp.onreadystatechange = handleServerResponse;
        xmlHttp.send(null);
      }catch(e) {
        alert( e.toString() );
      }
    }
}

function handleServerResponse() {
    theDiv = document.getElementById("theDiv");
    if(xmlHttp.readyState==1) {
        theDiv.innerHTML += "Status 1: server connection established <br/>";
    }else if(xmlHttp.readyState==2) {
        theDiv.innerHTML += "Status 2: request received <br/>";
    }else if(xmlHttp.readyState==3) {
        theDiv.innerHTML += "Status 3: processing request <br/>";
    }else if(xmlHttp.readyState==4) {

        if(xmlHttp.status==200) {
          try{
            text = xmlHttp.responseText;
            theDiv.innerHTML += "Status 4: request is finished and response is ready <br/>";
            theDiv.innerHTML += text;
          }catch(e){
            alert( e.toString() );
        }
        }else{
            alert( xmlHttp.statusText );
        }
    }
}

对不起长代码。 我真的很迷茫,所以我真的很感激任何帮助!

我只是复制了你的源代码并在我自己的服务器上运行它。 它完全没有问题。 我也制作了自己的“Practice.txt”文件。 没问题。

我将脚本放在body的末尾,并将封装的process()包装在其中; 我还从process()取走了闭包,并将process()作为onload处理程序内联到body标签,就像你一样。 再一次,没有问题。

因此,以下是您遇到问题的一些可能原因:

  1. “Practice.txt”与请求它的文档位于同一目录中吗?
  2. 您的服务器中是否有某些配置不允许您请求该特定资源?
  3. 是因为某些奇怪的原因,你的脚本是外部的并且在head造成了一些奇怪的问题?
  4. 除了“Practice.txt”之外,您是否尝试过请求任何其他资源? 是这样,结果是什么?
  5. 最后......你的服务器是? 必须在那里扔那个(我假设服务器已启用,但谁知道。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM