这个代码出了什么问题?(AJAX)



我的代码似乎不起作用,即与服务器通信。有人能告诉我我犯了什么样的错误吗?我监督了什么吗?

第页。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>

您的代码非常好。只需检查您在xmlhttp.open中作为第二个参数传递的url("GET","ajax_info.txt",true)。很可能您传递的文件名不正确。

要检查,您的代码是否正常工作,只需将ajax_info.txturl替换为https://api.github.com/users/octocat或任何其他可公开访问的api url或任何本地存储文件的名称(只需确保下次传递正确的名称)。

"与服务器通信":基本上,您在这里传递的是本地文件名,这就是它不与服务器通信的原因。为了让它与服务器通信,传递实际的url,就像上面的Github url一样。

最新更新