[英]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
标签,就像你一样。 再一次,没有问题。
因此,以下是您遇到问题的一些可能原因:
head
造成了一些奇怪的问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.