我想写一个简单的ajax局部刷新的例子,点击按钮后把一个txt文本文件的内容加载进来替换原有的内容,代码是这样的:
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","a.txt",true);
xmlhttp.send();
}
</script>
</head>
<body><h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div></body>
</html>
这个html文件和txt文件在同一个文件夹下,不知道什么原因实现不了,请指点,刚开始学习ajax,很多不懂的。 

解决方案 »

  1.   

    XMLHttpRequest的status属性一直为0,网上搜了也没有解决,你有什么方法能帮我解决一下吗?
      

  2.   

    看你的代码没有问题,你申明xmlhttp这个变量了吗?
      

  3.   

    <button type="button" onclick="loadXMLDoc()">请求数据</button>
    <div id="myDiv"></div>
    <script language="javascript" type="text/javascript">
        function loadXMLDoc(){
            var xmlhttp = false;
            if (window.XMLHttpRequest)xmlhttp = new XMLHttpRequest(); else if (window.ActiveXObject) {
                var B = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0"];
                for (var C = 0; C < B.length; C++) {
                    try {
                        xmlhttp = new ActiveXObject(B[C]);
                        break
                    } catch (F) {
                        alert("不支持 AJAX!")
                    }
                }
            }
            if (xmlhttp) {
                xmlhttp.open( "GET","a.txt", true);
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                    }
                };
                xmlhttp.send(null);
            }
        }
    </script>
    同时注意,ajax必须在网络中运行,不能是本地运行。比如你打开 D:\newsSite\test\0.html 运行ajax会提示拒绝访问,必须用 http://访问
      

  4.   

    var xmlhttp = new XMLHttpRequest() || new ActiveXObject("^-^"||"MSXML2.XMLHTTP"||"Microsoft.XMLHTTP"||"MSXML2.XMLHTTP.5.0"||"MSXML2.XMLHTTP.4.0"||"MSXML2.XMLHTTP.3.0") || null;