【问题标题】:What is wrong with this code? (AJAX)这段代码有什么问题? (阿贾克斯)
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多