使用ajax的代码有什么问题?

时间:2014-09-01 07:40:02

标签: javascript ajax

我对编码很陌生,现在我正在尝试编写一个代码,将文本数据形成一个文件,并用新文本替换当前文本。我使用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>

4 个答案:

答案 0 :(得分:1)

问题是onreadystatechange中的if-block。在请求和响应期间,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和onerror)更为简单,如here所述。

答案 1 :(得分:0)

1-包括1个与jquery-1.9.0.js相同的jQuery文件jquery-1.9.0.min.js,但jquery-1.9.0.min.js是缩小文件

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

3-您正在使用jQuery,所以当jQuery XMLHttpRequest已经为所有浏览器使用最好的HttpRequest时,为什么要使用$.get

你可以用这个

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

});
<script>

答案 2 :(得分:0)

您使用的是网络服务器吗? Ajax不能使用本地文件url:&#39; file://...'

答案 3 :(得分:0)

alert(" there is a error in your code"); 实际上你的代码没有错误。在请求的不同状态中调用xmlhttp.onreadystatechange。这就是你检查xmlhttp.readyState == 4的原因。在此处详细了解不同阶段:http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp 因此,您的代码运行正常,您只需提醒错误消息,这根本不是错误。