ajax服务器响应
一:服务器响应 获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。 属性 描述 responseText 获得字符串形式的响应数据。 responseXML 获得 XML 形式的响应数据。
responseText 属性 如果来自服务器的响应并非 XML,请使用 responseText 属性。 responseText 属性返回字符串形式的响应,因此您可以这样使用: document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
responseXML 属性 如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性: 请求 books.xml 文件,并解析响应 book.xml <bookstore> <bookcategory="children"> <titlelang="en">HarryPotter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <bookcategory="cooking"> <titlelang="en">EverydayItalian</title> <author>Giada DeLaurentiis</author> <year>2005</year> <price>30.00</price> </book> <bookcategory="web"cover="paperback"> <titlelang="en">LearningXML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> <bookcategory="web"> <titlelang="en">XQueryKick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>VaidyanathanNagarajan</author> <year>2003</year> <price>49.99</price> </book> </bookstore>
ajax脚本:
xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; } document.getElementById("myDiv").innerHTML=txt;
二:onreadystatechange 事件 当请求被发送到服务器时,我们需要执行一些基于响应的任务。 每当 readyState 改变时,就会触发 onreadystatechange 事件。 readyState 属性存有 XMLHttpRequest 的状态信息。 下面是 XMLHttpRequest 对象的三个重要的属性:
属性 描述 onreadystatechange 存储函数(或函数名),每当readyState 属性改变时,就会调用该函数。 readyState 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。 0: 请求未初始化 1: 服务器连接已建立 2: 请求已接收 3: 请求处理中 4: 请求已完成,且响应已就绪 status 200: "OK" 404: 未找到页面
使用 Callback 函数 callback 函数是一种以参数形式传递给另一个函数的函数。 如果您的网站上存在多个 AJAX 任务,那么您应该为创建 XMLHttpRequest 对象编写一个标准的函数,并为每个 AJAX 任务调用该函数。
三:入门案例 <!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <scripttype="text/javascript"> //ajax核心对象名称 varxmlhttp; //创建XMLHttpRequest核心对象 functioncreateXMLHttp(){ //判断使用的浏览器类型 if(window.XMLHttpRequest){ //支持的浏览器类型IE7+,Firefox,Chrome,Opera,Safari xml=newXMLHttpRequest(); } else{ //支持的浏览器类型 IE6,IE5 xml=newActiveXObject("Microsoft.XMLHTTP"); } } functionshowMsg(){ //创建xmlhttp核心对象 createXMLHttp(); //设置一个请求 xmlhttp.open("get","test1.txt"); //设置请求完成之后处理的回调函数 xmlhttp.onreadystatechange=showMsgCallBack; //发送请求不传递任何函数 xmlhttp.send(null); } //定义回调函数 functionshowMsgCallBack(){ //数据返回完毕 if(xmlhttp.readyState==4){ //http操作正常 if(xmlhttp.status==200){ //接受返回的内容 vartext=xmlhttp.responseText; //设置使用的css样式表 document.getElementById("msg").innerHTML=text; } } } </script> <body> <input type="button"value="调用ajax显示内容" onClick="showMsg()"> <spanid="msg"></span> </body> </html> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |