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



我的.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:A network error occured"。我认为这可能是由脚本中的第一个警报触发的。我使用了一个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. 最后。。。你的服务器在上吗?必须把那个扔进去(我想服务器是开着的,但谁知道呢。)

最新更新