Javascript XMLHttpRequest不工作-无错误
我正试图让这个简单的请求生效,但我运气不太好。 我在服务器文件夹中有一个“test.txt”文件作为包含下面提供的脚本的html文件 我在Chrome、Firefox和IE11中查看了该文件,结果相同。我只能从html页面中看到“html页面中的初始文本…”文本。没有错误,并且未显示my test.txt文件中的文本 有人能告诉我我的代码有什么问题吗Javascript XMLHttpRequest不工作-无错误,javascript,html,Javascript,Html,我正试图让这个简单的请求生效,但我运气不太好。 我在服务器文件夹中有一个“test.txt”文件作为包含下面提供的脚本的html文件 我在Chrome、Firefox和IE11中查看了该文件,结果相同。我只能从html页面中看到“html页面中的初始文本…”文本。没有错误,并且未显示my test.txt文件中的文本 有人能告诉我我的代码有什么问题吗 <!DOCTYPE html> <html> <head> <script type="te
<!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>
var xmlHttp=createXmlHttpRequestObject();
函数createXmlHttpRequestObject(){
var xmlHttp
如果(window.XMLHttpRequest){
xmlHttp=新的XMLHttpRequest();
}
否则{
xmlHttp=新的ActiveXObject(“Microsoft.xmlHttp”);
}
返回xmlHttp:
}
函数过程(){
if(xmlHttp){
试试{
open(“GET”、“test.txt”、true);
xmlHttp.onreadystatechange=handleServerResponse;
xmlHttp.send(空);
}
捕获(e){
警惕(如toString());
}
}
}
函数handleServerResponse(){
output=document.getElementById('output');
if(xmlHttp.readyState==1){
output.innerHTML+=“状态1:已建立服务器连接
”
}
else if(xmlHttp.readyState==2){
output.innerHTML+=“状态2:收到请求
”
}
else if(xmlHttp.readyState==3){
output.innerHTML+=“状态3:服务器处理
”
}
else(xmlHttp.readyState==4){
if(xmlHttp.status=200){
试一试{
text=xmlHttp.responseText;
output.innerHTML+=“状态4:请求已完成,响应已准备就绪
”
output.innerHTML+=文本;
}
第(e)款{
警惕(如toString());
}
}
否则{
警报(xmlHttp.statusText);
}
}
}
html页面中的初始文本..
好的,我想出来了
这是一个拼写错误和一个提示
return xmlHttp: -> should be ; instead
忘了“其他”
有两件事,请确保在变量声明之前先使用
var
,其次,您是否尝试过在浏览器的调试器中设置断点?在chrome中,只需按住shift-cntrl-i即可启动devtools@Jared史密斯-谢谢你的提示。我追根究底,并发布了一份决议作为答案。
else(xmlHttp.readyState==4){ -> should be else if (xmlHttp.readyState==4){