AJAX+JSP实现读取XML内容并按排列显示输出的方法示例
本文实例讲述了AJAX+JSP实现读取XML内容并按排列显示输出的方法。分享给大家供大家参考,具体如下:
实现功能:点击按扭,显示出JSP页面中通过out.println传过来的xml信息
一、含XML的JSP页面
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%> <% response.setContentType("text/xml"); Stringtxt=request.getParameter("username"); out.println(""); %> 张三 21 男
二、AJAX处理并显示返回页面
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%>ajax02 /* ajax的几个步骤: 1、建立XmlHttpRequest对象 2、设置回调函数 3、使用Open方法建立与服务器的连接 4、向服务器发送数据 5、在回调函数中针对不同响应状态进行处理 */ varxmlHttp; functioncreateXMLHttpRequest(){//1建立XmlHttpRequest对象 if(window.ActiveXObject){ try{ alert("Msxml2.XmlHttp.5.0"); xmlHttp=newActiveXObject("Msxml2.XmlHttp.5.0"); }catch(e){ try{ xmlHttp=newActiveXObject("Microsoft.XMLHttp"); }catch(e){ alert("Microsoft.XMLHttp"); } } }else{ xmlHttp=newXMLHttpRequest(); } } functionshowMes(){//2设置回调函数 if(xmlHttp.readyState==4){//数据接收完成并可以使用 if(xmlHttp.status==200){//http状态OK //5、在回调函数中针对不同响应状态进行处理 //document.getElementById("sp").innerHTML=xmlHttp.responseText;//服务器的响应内容 varname=xmlHttp.responseXML.getElementsByTagName("name")[0].firstChild.nodeValue; varage=xmlHttp.responseXML.getElementsByTagName("age")[0].firstChild.nodeValue; varsex=xmlHttp.responseXML.getElementsByTagName("sex")[0].firstChild.nodeValue; document.getElementById("spanname").innerHTML=name; document.getElementById("spanage").innerHTML=age; document.getElementById("spansex").innerHTML=sex; }else{ alert("出错:"+xmlHttp.statusText);//HTTP状态码对应的文本 } } } /** //这是GET方法传送 functiongetMes(){ createXMLHttpRequest(); vartxt=document.getElementById("txt").value; varurl="servlet/AjaxServlet?txt="+txt; url=encodeURI(url);//转换码后再传输 xmlHttp.open("GET",url,true);//3使用Open方法建立与服务器的连接 xmlHttp.onreadystatechange=showMes; xmlHttp.send(null);//4向服务器发送数据 } */ /** *这是post方法 */ functionpostMes(){ createXMLHttpRequest(); vartxt=document.getElementById("txt").value; //varurl="servlet/AjaxServlet"; varurl="work02forxml-2.jsp" varparams="username="+txt; xmlHttp.open("POST",url,true); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xmlHttp.send(params); xmlHttp.onreadystatechange=showMes; }
姓名:
年龄:
性别:
PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:
在线