使用ajax的这段代码有什么问题

What is wrong with this code using ajax?

本文关键字:代码 什么 问题 ajax 段代码 使用      更新时间:2023-09-26

我是编码新手,现在我正试图编写一段代码,从文件中获取文本数据,并用新文本替换当前文本。我使用AJAX来完成这项任务,但问题是首先我得到了错误消息,然后是预期的答案。错误消息是我在代码中包含的内容,当出现错误时会显示。尽管我得到了想要的答案,但我想知道为什么会显示错误消息。这是我的代码

<!DOCTYPE html>
<html>   
<head>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
    <script>
        function loadXML() {
            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("p1").innerHTML = xmlhttp.responseText;
                }
                else {
                    alert(" there is a error in your code");  
                }   
            }
            xmlhttp.open("GET","robots.txt", true);
            xmlhttp.send(null);
        }
    </script>
</head>    
<body>
    <p id="p1">This is Text</p>
    <button id="b1" onclick="loadXML()">Click me </button>
</body>
</html>

问题在于onreadystatechange中的if块。在请求和响应过程中,xmlhttp.readyState多次更改,每次发生这种情况时都会调用onreadystatechange。

如果你这样做,它可能会起作用:

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 ) {
         if( xmlhttp.status == 200 ) {
             document.getElementById("p1").innerHTML = xmlhttp.responseText;
         } else {
             alert(" there is a error in your code");  
         }
    }   

然而,使用其他事件方法(如onload和oneror)更简单,如本文所述。

1-包含1个jQuery文件jquery-1.9.0.jsjquery-1.9.0.min.js相同,但jquery-1.9.0.min.js是缩小文件

2-javaconsole日志中的错误消息是什么?

3-您使用的是jQuery,所以为什么您使用XMLHttpRequest,而jQuery $.get已经为所有浏览器使用了最好的HttpRequest

你可以用这个替换你的JS代码

<script type="text/javascript">
$( document ).ready(function() {
        $.get('robots.txt',function(data){ $('#p1').html(data) });
});
<script>

您在使用Web服务器吗?Ajax无法从本地文件url运行:'file://...'

alert(" there is a error in your code");实际上,您的代码中没有错误。CCD_ 7在请求的不同状态下被调用。这就是您检查xmlhttp.readyState == 4的原因。在此处了解有关不同阶段的更多信息:http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp所以你的代码运行得很好,你只是提醒一条错误消息,这根本不是错误。