日期:2014-05-16  浏览次数:20612 次

Ajax例子错误? - Web 开发 / Ajax
最经我在看一本Ajax基础教程,里面有一个例子:
<%@ page language="C#" autoeventwireup="true" inherits="_Default, App_Web_pudn8gg9" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>无标题页</title>
  <script type="text/javascript" language="javascript">
var xmlHttp;
//创建XMLHttpRequest对象
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}

function startRequest()  
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET","simpleResponse.xml",true);
xmlHttp.send(null);
}

function handleStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
alert("The server replied width:" + xmlHttp.responseText);
}
}
}
</script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
  <input type="button" value="Start Basic Asynchronuos Request" onclick="startRequest()" />
  </div>
  </form>
</body>
</html>

这是整个Default.aspx文件,运行起来有一个button。
但是单击是却没有效果,

我快速监视onreadystatechange的时候老师说什么未定义。


请高手指点,错误出在什么地方???

------解决方案--------------------
function startRequest() 
{
少了个括号
------解决方案--------------------
如果在本地运行(如:C:\ajax\test.htm),那么status属性不管是在”成功”还是”页面未找到”的情况下,都返回的是0,而不是200和404。这个时候如果还用if(xmlHttp.status==200)来判断运行,则会毫无结果。如果要在本地测试,最好写成if(xmlHttp.status== 200 || xmlHttp.status==0)的形式来判断。
------解决方案--------------------
感觉是ie缓存的问题

try
JScript code
xmlHttp.open("GET","simpleResponse.xml?_dc="+new Date().getTime(),true);//加时间戳

------解决方案--------------------
createXMLHttpRequest()你既然把 创建http 对象封装成函数,那么你这个函数在哪里调用了,你的函数没调用,自然对象不存在。
JScript code
    var xmlHttp = false;
        try {
          xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
          try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e2) {
            xmlHttp = false;
          }
        }
        if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
          xmlHttp = new XMLHttpRequest();
        }

------解决方案--------------------
学习了。楼上说的好像有道理。