实例解读Ajax与servlet交互的方法
投稿:shichen2014
这篇文章主要介绍了Ajax与servlet交互的方法,需要的朋友可以参考下
本文以实例形式剖析了Ajax与servlet的交互,并且代码中有较为详细的注释,以帮助大家阅读理解。具体的实现方法如下:
1.JavaScript部分
var req; /*通过异步传输XMLHTTP发送参数到ajaxServlet,返回符合条件的XML文档*/ var url; function getResult() { var f=document.getElementById("form_pub"); var key=f.s.options[f.s.selectedIndex].text; //获取对select中文本的引用 if (window.XMLHttpRequest) { req = new XMLHttpRequest(); url = "ajaxServlet?action="+key+"&bm=UTF-8"; }else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); url = "ajaxServlet?action="+key+"&bm=gbk"; } if(req) { req.open("GET",url, true); req.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); //这里如果不设定头部则会导致 firfox 发送数据错误,servlet接受到的参数为乱码,在IE中正常 req.onreadystatechange = complete; req.send(null); //req.setRequestHeader("Content-Type", "text/xml; charset=UTF-8"); } } /*分析返回的XML文档*/ function complete(){ if (req.readyState == 4) { if (req.status == 200) { var items=document.getElementById("belong"); //以下为解析返回的XML文档 var xmlDoc = req.responseXML; var Node=xmlDoc.getElementsByTagName("type_name"); //var str=new Array(); var str=null; //清空工作 items.innerHTML=""; //删除一个 select内的全部内容 for(var i=0;i<Node.length;i++) { str=Node[i]; //alert(str.childNodes[0].nodeValue); var objectOption=document.createElement("option"); items.options.add(objectOption); //firfox不支持innerText必须用textContent代替 if (window.ActiveXObject) {objectOption.innerText=str.childNodes[0].nodeValue;} else {objectOption.textContent=str.childNodes[0].nodeValue;} } } } }
2.servlet端:
package ajax; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Data_GetConn.GetConn;//这个包是自己写的为获取对mysql的引用 import java.sql.*;//这个包必须有!! public class ajaxServlet extends HttpServlet{ //private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";//这里最好统一用UTF-8进行编码 public void init() throws ServletException{} public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml; charset=UTF-8"); //以下两句为取消在本地的缓存 response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); PrintWriter out = response.getWriter(); String action = request.getParameter("action"); String bm = request.getParameter("bm"); if(("gbk").equals(bm)) { action=new String(action.getBytes("ISO-8859-1"),"gbk");//将获得的数据用gbk从新编码!(感谢董卫老师) } else { action=new String(action.getBytes("ISO-8859-1"),"gbk"); } try { GetConn wq=new GetConn(); Connection con=wq.getCon(); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select items from class where main='"+action+"'"); StringBuffer sb = new StringBuffer(); sb.append("<type>"); while(rs.next()) { sb.append("<type_name>"+rs.getString(1)+"</type_name>"); } //sb.append("<type_name>"+action+"</type_name>"); sb.append("</type>"); out.write(sb.toString());//注意这里向jsp输出的流,在script中的截获方法 out.close(); stmt.close(); con.close(); } catch(Exception ex) { } } }