0

我是 AJAX 的新手,所以我在制作一个简单的 AJAX 程序时遇到了很多问题。我有一个按钮,我想做的是,当我单击它时,它下面的 div 的文本会发生变化。我尝试了很多次,但仍然找不到错误。

这是我的代码:

<html>
  <head>
    <script>
        function loadXMLDoc() {
            var xmlhttp;

            if(!window.XMLHttpRequest) {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } else {
                xmlhttp = new XMLHttpRequest();
            }

            xmlhttp.onReadyStateChange = function () {
                if(xmlhttp.readyState==2 && xmlhttp.status==200) {
                    document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
                }
            };

            xmlhttp.open('GET', 'textfile.txt', true);
            xmlhttp.send();
        }
    </script>
  </head>
  <body>
    <button type="button" value="Click!" onClick="loadXMLDoc();">Hello World</button>
    <div id='myDiv'>hello!</div>
  </body>
</html>

这是文本文件:

<p>My name is areeb siddiqui</p>
<p>My name is areeb siddiqui</p>

任何帮助,将不胜感激

提前致谢 :)

这也是我的网页: http: //mytestingsite.site90.net/ajax/

4

4 回答 4

1

更改此块:

if(xmlhttp.readyState==4 && xmlhttp.status==200)
于 2013-02-01T16:37:05.093 回答
1

这应该对你有用..这就是我提出我的ajax请求的方式..非常相似

function loadXMLDoc() {
    var xmlhttp = null;

    if(!window.XMLHttpRequest) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        xmlhttp = new XMLHttpRequest();
    }

    xmlhttp.open('GET', 'textfile.txt', true);
    xmlhttp.send();

    xmlhttp.onreadystatechange = function()
    {
        if(xmlhttp.readyState != 4 || xmlhttp.status != 200){return;}
        document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
    }

}

您的函数未更新的原因是因为onreadystatechange必须全部小写

于 2013-02-01T17:03:53.167 回答
0

check onreadystatechange

 xmlhttp.onreadystatechange = function () {
        if(xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
        }
    };
于 2013-02-01T17:10:51.747 回答
0

用 onreadystatechange 改变 onReadyStateChange 和用 xmlhttp.readyState==4 改变 xmlhttp.readyState==2

于 2013-02-01T17:11:16.303 回答