XMLHttpRequest 对象响应服务器
onreadystatechange 事件@H_404_3@ 当请求被发送到服务器时,我们需要执行一些基于响应的任务。@H_404_3@ 每当 readyState 改变时,就会触发 onreadystatechange 事件。@H_404_3@ readyState 属性存有 XMLHttpRequest 的状态信息。@H_404_3@ 下面是 XMLHttpRequest 对象的三个重要的属性:@H_404_3@ onreadystatechange存储函数(或函数名) ,每当 readyState 属性改变时,就会调用该函数。@H_404_3@ readyState@H_404_3@ 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。@H_404_3@ 0: 请求未初始化@H_404_3@ 1: 服务器连接已建立@H_404_3@ 2: 请求已接收@H_404_3@ 3: 请求处理中@H_404_3@ 4: 请求已完成,且响应已就绪@H_404_3@ status@H_404_3@ 200: "OK"@H_404_3@ 404: 未找到页面@H_404_3@ 在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。@H_404_3@ 如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。@H_404_3@ 属性 描述@H_404_3@ responseText 获得字符串形式的响应数据。@H_404_3@ responseXML 获得 XML 形式的响应数据。 (了解即可)@H_404_3@
<script type="text/javascript"> function loadName(){ var xmlHttp; if(window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); }else{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status); xmlHttp.onreadystatechange=function(){ alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status); if(xmlHttp.readyState==4 && xmlHttp.status==200){ alert(xmlHttp.responseText); document.getElementById("name").value=xmlHttp.responseText; } }; // xmlHttp.open("get","getAjaxName?name=jack&age=11",true); // xmlHttp.open("post",true); // xmlHttp.send(); xmlHttp.open("post","getAjaxName",true); xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send("name=jack&age=11"); } </script>