我正在尝试让这个简单的请求正常工作,但我运气不佳。 我的服务器文件夹中有“test.txt”文件作为我的 html 文件,其中包含下面提供的脚本。
我在 Chrome、Firefox 和 IE11 中查看了该文件,结果相同。我只能从 html 页面看到“html 页面中的初始文本..”文本。没有错误,并且我的 test.txt 文件中的文本没有显示。
有人可以指出我的代码有什么问题吗?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
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","test.txt", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
catch(e){
alert( e.toString() );
}
}
}
function handleServerResponse(){
output = document.getElementById('output');
if(xmlHttp.readyState==1){
output.innerHTML += "Status 1: server connection established <br />"
}
else if(xmlHttp.readyState==2){
output.innerHTML += "Status 2: request received <br />"
}
else if(xmlHttp.readyState==3){
output.innerHTML += "Status 3: server processing <br />"
}
else(xmlHttp.readyState==4){
if(xmlHttp.status=200){
try{
text = xmlHttp.responseText;
output.innerHTML += "Status 4: request is finished and response is ready<br />"
output.innerHTML += text;
}
catch(e){
alert( e.toString() );
}
}
else{
alert( xmlHttp.statusText );
}
}
}
</script>
</head>
<body onload="process()">
Initial text in the html page..<br>
<br>
<div id="output">
</div>
</body>
</html>
最佳答案
好吧,我明白了......
这是一个拼写错误和一个遗漏
return xmlHttp: -> should be ; instead
忘记了“else”
else(xmlHttp.readyState==4){ -> should be else if (xmlHttp.readyState==4){
关于javascript - XMLHttpRequest 不工作 - 没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26300288/