【发布时间】:2017-01-15 06:38:18
【问题描述】:
我的代码似乎不起作用,即与服务器通信。 有人可以告诉我我犯了什么样的错误吗?我监督了什么?
P.S – AJAX 新手。
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("mySection").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<section id="mySection">
<h2>Let AJAX change this text</h2>
</section>
<button onclick="loadXMLDoc()" type="button">Change Content</button>
</body>
</html>
【问题讨论】:
-
做一些基本的调试。在浏览器中打开开发者工具。看看控制台。它说什么?查看网络选项卡。你看到请求了吗?你看到回应了吗?他们是你所期待的吗?添加
console.log语句。onreadystatechange被调用了吗? readyState 和 status 得到什么值? -
这似乎运行得很好。 ajax_info.txt 是否在同一目录中?你确定你上传了吗?请记住,如果您在本地运行它,您可能会在控制台
XMLHttpRequest cannot load file:///C:/Users/*******/Desktop/ajax_info.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.中收到此错误
标签: javascript html ajax xmlhttprequest